Image Upload Problem to Firebase in Flutter "type 'XFile' is not a subtype of type 'File'"

Issue

I working on a project with Firebase-Flutter. I have problem with Image Upload to Firebase. When i select picture from gallery, it doesn’t working. I catch this problem: " type ‘XFile’ is not a subtype of type ‘File". Where is my error and how can i solve this problem?

Here is my codes.

class AddStatus extends StatefulWidget {
final String currentUserId;
const AddStatus({ Key? key,required this.currentUserId }) : super(key: key);

@override
State<AddStatus> createState() => _AddStatusState();
}

class _AddStatusState extends State<AddStatus> {
late String _tweetText;
i.File? _pickedImage;
bool _loading = false;
final ImagePicker _picker = ImagePicker();

handleImageFromGallery() async {
try {
  i.File imageFile =
      (await _picker.pickImage(source: ImageSource.gallery)) as dynamic;
  if (imageFile != null) {
    setState(() {
      _pickedImage = i.File(_pickedImage!.path);
      
     _pickedImage = i.File( imageFile.path );
      
    });
  }
  } catch (e) {
  print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
  backgroundColor: Colors.white,
  appBar: AppBar(
    
    centerTitle: true,
    title: Text(
      'Durum',
      style: TextStyle(
        color: Colors.white,
        fontSize: 20,
      ),
    ),
  ),
  body: Padding(
    padding: const EdgeInsets.symmetric(horizontal: 20),
    child: Column(
      children: [
        SizedBox(height: 20),
        TextField(
          maxLength: 280,
          maxLines: 7,
          decoration: InputDecoration(
            hintText: 'Ne düşünüyorsun...',
          ),
          onChanged: (value) {
            _tweetText = value;
          },
        ),
        SizedBox(height: 10),
        _pickedImage == null
            ? SizedBox.shrink()
            : Column(
                children: [
                  Container(
                    height: 200,
                    decoration: BoxDecoration(
                        color: Colors.black,
                        image: DecorationImage(
                          fit: BoxFit.cover,
                          image: FileImage(_pickedImage!),
                        )),
                  ),
                  SizedBox(height: 20),
                ],
              ),
        GestureDetector(
          onTap: handleImageFromGallery,
          child: Container(
            height: 70,
            width: 70,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              color: Colors.white,
              border: Border.all(
                color: Colors.amber,
                width: 2,
              ),
            ),
            child: Icon(
              Icons.camera_alt,
              size: 50,
              color: Colors.amber,
            ),
          ),
        ),
        SizedBox(height: 20),
        RoundedButton(
          btnText: 'Paylaş',
          onBtnPressed: () async {
            setState(() {
              _loading = true;
            });
            if (_tweetText != null && _tweetText.isNotEmpty) {
              String image;
              if (_pickedImage == null) {
                image = '';
              } else {
                image =
                    await StorageService.uploadTweetPicture(_pickedImage!);
              }
              Status tweet = Status(
                text: _tweetText,
                image: image,
                authorId: widget.currentUserId,
                likes: 0,
               
                timestamp: Timestamp.fromDate(
                  DateTime.now(),
                ), id: '',
              );
              DatabaseServices.createTweet(tweet);
              Navigator.pop(context);
            }
            setState(() {
              _loading = false;
            });
          },
        ),
        SizedBox(height: 20),
        _loading ? CircularProgressIndicator() : SizedBox.shrink()
      ],
     ),
    ),
  );
 }
 }

here is my storage service codes`

static Future<String> uploadTweetPicture(File imageFile) 
async {
String uniquePhotoId = Uuid().v4();
File? image = await compressImage(uniquePhotoId, imageFile);

UploadTask uploadTask = storageRef
    .child('images/tweets/tweet_$uniquePhotoId.jpg')
    .putFile(image!);
TaskSnapshot taskSnapshot = await uploadTask.whenComplete(() => null);
String downloadUrl = await taskSnapshot.ref.getDownloadURL();
return downloadUrl;
}

static Future<File?> compressImage(String photoId, File image) async {
final tempDirection = await getTemporaryDirectory();
final path = tempDirection.path;
File? compressedImage = await FlutterImageCompress.compressAndGetFile(
  image.absolute.path,
  '$path/img_$photoId.jpg',
  quality: 70,
 );
 return compressedImage;
}`

Solution

I guess you need to create File from XFile

myFile = File(myXFile.path)

Answered By – Ulmasbek rakhmatullaev

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *