Home > Blockchain >  Why is my flutter Future<String> async function returning a null string?
Why is my flutter Future<String> async function returning a null string?

Time:11-23

 Future<String> upload_to_server(File image) async {
    var file;
    String str;
    String filename = image.path.split('/').last;
    FormData formData = new FormData();
    file = await MultipartFile.fromFile(image.path,
        filename: filename, contentType: MediaType('image', 'jpeg'));
    formData.files.add(MapEntry('photo', file));

      Response response =
          await Dio().post("http://10.0.2.2:5000/", data: formData);
      if (response.statusCode == 200) str = jsonDecode(response.data.toString());

    print(str);
    return str;
  }

This function is returning a null string however when I print the value of the string I am getting a non null string output. I believe the problem might be with json decoding. Could somebody help me figure this out?

CodePudding user response:

the problem is occurred because you try to decode response.data

Future<String> upload_to_server(File image) async {
var file;
String str;
String filename = image.path.split('/').last;
FormData formData = new FormData();
file = await MultipartFile.fromFile(image.path,
    filename: filename, contentType: MediaType('image', 'jpeg'));
formData.files.add(MapEntry('photo', file));

  Response response =
      await Dio().post("http://10.0.2.2:5000/", data: formData);
  if (response.statusCode == 200) {
  str = response.data.toString();

print(str);
return str;
    }else{
throw Expression('Failed to Load Response');
        }

CodePudding user response:

With dio you do not have to use jsonDecode, response.data should give you the string.

str = response.data;

CodePudding user response:

Try this way if you want to decode:

dynamic str = jsonDecode(jsonEncode(response.data));

hope this work's

CodePudding user response:

You can try:

 var data = json.decode(json.encode(response.data));
  • Related