Ad

The Argument Type 'File?' Can't Be Assigned To The Parameter Type 'Future?'

- 1 answer

  File ? file;
  String status = '';
  String ? base64Image;
  File ? tmpFile;
  String errMessage = 'Error Uploading Image';

chooseImage() async {
      var image = await ImagePicker().pickImage(source: ImageSource.gallery);
      setState(() {
        file = File(image!.path);
      });
    setStatus('');
    print(base64Image);
  }

startUpload() {
    setStatus('Uploading Image...');
    if (null == tmpFile) {
      setStatus(errMessage);
      return;
    }
    String fileName = tmpFile!.path.split('/').last;
    upload(fileName);
  }
  setStatus(String message) {
    setState(() {
      status = message;
    });
  }

  upload(String fileName) {
    http.post(Uri.parse(URL), body: {
      "image": base64Image,
      "name": fileName,
    }).then((result) {
      setStatus(result.statusCode == 200 ? result.body : errMessage);
    }).catchError((error) {
      setStatus(error);
    });
  }


Widget showImage() {
    return FutureBuilder<File>(
      future: file,
      builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
        if (snapshot.connectionState == ConnectionState.done &&
            null != snapshot.data) {
          tmpFile = snapshot.data;
          base64Image = base64Encode(snapshot.data!.readAsBytesSync());
          return Flexible(
            child: Image.file(
              snapshot.data!,
              fit: BoxFit.fill,
            ),
          );
        } else if (null != snapshot.error) {
          return const Text(
            'Error Picking Image',
            textAlign: TextAlign.center,
          );
        } else {
          return const Text(
            'No Image Selected',
            textAlign: TextAlign.center,
          );
        }
      },
    );
  }

i am trying to pick a image and convert it to base64

Ad

Answer

You don't need to use FutureBuilder for using File instead just use this directly:

Widget showImage() {
  if (file != null) {
    tmpFile = file!;
    base64Image = base64Encode(file!.readAsBytesSync());
    return Flexible(
      child: Image.file(
        file!,
        fit: BoxFit.fill,
      ),
    );
  } else {
    return const Text(
      'No Image Selected',
      textAlign: TextAlign.center,
    );
  }
}```
Ad
source: stackoverflow.com
Ad