0

I am working on a Flutter app to take image from gallery and predict the appropriate output via detection using the model I trained using Machine learning but, I am getting an error for this following code:

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tflite/tflite.dart';

void main() {
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    theme: ThemeData.dark(),
    home: HomePage(),
  ));
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  late bool _isLoading;
  late File _image;
  late List _output;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _isLoading = true;
    loadMLModel().then((value){
      setState(() {
        _isLoading = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Brain Tumor Detection"),
      ),
      body: _isLoading ? Container(
        alignment: Alignment.center,
        child: CircularProgressIndicator(),
      ) : SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _image == null ? Container() : Image.file(File(_image.path)),
            SizedBox(height: 16,),
            _output == null ? Text(""): Text(
                "${_output[0]["label"]}"
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          chooseImage();
        },
        child: Icon(
            Icons.image
        ),
      )
      ,
    );
  }

  chooseImage() async {
    final image = await ImagePicker().pickImage(source: ImageSource.gallery);
    if (image == null) return null;
    setState(() {
      _isLoading = true;
      _image = image as File;
    });
    runModelOnImage(image);
  }

  runModelOnImage(File image) async{
    var output = await Tflite.runModelOnImage(
        path: image.path,
        numResults: 2,
        imageMean: 127.5,
        imageStd: 127.5,
        threshold: 0.5
    );
    setState(() {
      _isLoading = false;
      _output = output!;
    });
  }


  loadMLModel() async {
    await Tflite.loadModel(
        model: "assets/btc.tflite",
        labels: "assets/labels.txt"
    );
  }
}

The error is:

The argument type 'XFile' can't be assigned to the parameter type 'File'.

I have tried all the other alternatives given out there for imagepicker issues faced by other people. Any help to solve this would be great! Thank you in advance!!

Pratishtha S
  • 81
  • 2
  • 11
  • Does this answer your question? [A value of type 'XFIle' can't be assigned to a variable of type 'File' error](https://stackoverflow.com/questions/69896148/a-value-of-type-xfile-cant-be-assigned-to-a-variable-of-type-file-error) – tareq albeesh Mar 31 '22 at 11:59
  • I already tried that – Pratishtha S Mar 31 '22 at 12:08

3 Answers3

1
chooseImage() async {
    final image = await ImagePicker().pickImage(source: ImageSource.gallery);
    if (image == null) return null;
    setState(() {
      _isLoading = true;
      _image = File(image.path);
    });
   runModelOnImage(_image);
}
saytoonz
  • 186
  • 6
1

I was facing the same issue. What I did was:

  • Created a variable of XFile in my widget XFile? _image; Look at this function
Future getImageFromGallery() async {
    _image = await ImagePicker()
        .pickImage(source: ImageSource.gallery, maxHeight: 300, maxWidth: 300);
    if (_image!.path.isNotEmpty) {
      setState(() {
        pickedImage = true;
      });
    }
  }
  • On the press of a button, called the above function.

  • Used the follwing function to upload file on Firebase storage

  Future uploadLogo(BuildContext? context, XFile? image) async {
      FirebaseStorage storage = FirebaseStorage.instance;
      Reference ref = storage
          .ref()
          .child('shops/${_name.text}/Logo${DateTime.now().toString()}');


      final path = image!.path; //Getting the path of XFile
      File file = File(path);// Turning that into File
      UploadTask uploadTask = ref
          .putFile(file); //Getting a proper reference to upload on storage

      final TaskSnapshot downloadUrl = (await uploadTask); //Uploading to //storage

      imageUrlShop = await downloadUrl.ref.getDownloadURL();
  }

My answer is almost same as of the earlier ones but there is a little change in the format and how the argument is being passed. This is working for me. Might work for you too...

Bilal Saeed
  • 2,092
  • 8
  • 31
0

You are calling runModelOnImage which takes a File as an argument, with an XFile.

chooseImage() async {
  final image = await ImagePicker().pickImage(source: ImageSource.gallery);
  if (image == null) return null;
  setState(() {
    _isLoading = true;
    _image = File(image.path);
  });
  runModelOnImage(_image);
}
Rukka
  • 350
  • 1
  • 9