Home > Software engineering >  Instance of 'Future' return instead of return some value
Instance of 'Future' return instead of return some value

Time:09-07

I have a function, which is called on one page, I need to return some value e.g status code or a string to the previous page for some calculation where I am calling this function. but I get Instance of 'Future' instead of value. I feel trouble figuring out what I am missing here.

class Update {
  Future updateData(
      String name,
      ) async {
        somedata={
          "name": name
        }
    String jsonBody = json.encode(somedata);
    await http
        .put(
      Uri.parse('Some API call'),
      body: jsonBody,
      headers: {
        some header
      },
    ).then(
          (response) {
        if (response.statusCode == 200) {
          return "sucess";
        }
        else if(response.statusCode == 401){
           return "Sign in again";
        }
      },
    ).catchError(
          (e) {
        if (kDebugMode) {
          Center(
            child: Text(
                "$e"
            ),
          );
        }
      },
    );
  }
}

Function calling on a page

var getResponce= Update().updateData(event_title.text,)
            print(getResponce);

Here on this print I get instance of future instead of value.

What I tried

class Update {
  Future<String?> updateData();

Here on this print, I get an instance of Future<String?> instead of value.

CodePudding user response:

In Order to get Future value you have to await for it, try this:

var getResponce= await Update().updateData(event_title.text,)
print(getResponce);

then change your Update to this:

class Update {
  Future updateData(String name) async {
    somedata={
      "name": name
    }
    String jsonBody = json.encode(somedata);
    var response = await http
        .put(Uri.parse('Some API call'), body: jsonBody
            headers: {
              some header
            },
            )
        .catchError(
      (e) {
        if (kDebugMode) {
          Center(
            child: Text("$e"),
          );
        }
      },
    );

    if (response.statusCode == 200) {
      return "sucess";
    } else if (response.statusCode == 401) {
      return "Sign in again";
    }
  }
}
  • Related