1

I'm trying to use flutter's FutureBuilder with an http.get() as the future parameter like so:

child: FutureBuilder(
  future: http.get(
      Uri.http('192.168.31.144:8000', 'api/v1/login')),
  builder: (context, snapshot) {
    if (snapshot.connectionState ==
        ConnectionState.done) {
      if (snapshot.hasError) {
        return Text('error');
      }
      return Text(snapshot.data);
    } else {
      return SpinKitFadingCircle(color: Colors.white);
    }
  },
),

I get the following error: The following _TypeError was thrown building FutureBuilder<Response>(dirty, state: _FutureBuilderState<Response>#0caa6): type 'Response' is not a subtype of type 'String'

From what I understand is that the FutureBuilder needs type Future<Response> as its future but http.get() is returning type String?

manchitro
  • 131
  • 1
  • 11

1 Answers1

0

you have yo await for your future to come

Future<dynamic> getData() async {
return await http.get(Uri.http('192.168.31.144:8000', 'api/v1/login');
}



 child: FutureBuilder(
      future: getData(),
      builder: (context, snapshot) {
        if (snapshot.connectionState ==
            ConnectionState.done) {
          if (snapshot.hasError) {
            return Text('error');
          }
          return Text(snapshot.data);
        } else {
          return SpinKitFadingCircle(color: Colors.white);
        }
      },
    ),
Moaid ALRazhy
  • 1,604
  • 1
  • 3
  • 13
  • I've tried this. It causes another 2 errors: 1 `The argument type 'Response' can't be assigned to the parameter type 'Future'` 2 `The await expression can only be used in an async function. Try marking the function body with either 'async' or 'async*'` – manchitro Apr 20 '21 at 11:55
  • I've edited the answer , add the function to your class and try now – Moaid ALRazhy Apr 20 '21 at 12:10
  • No need to await with a FutureBuilder! It essentially does that automatically on the future: parameter. But you have a different issue, because you're creating the Future on each call to build(), and that's problematic, as illustrated here: https://www.youtube.com/watch?v=sqE-J8YJnpg – Randal Schwartz Apr 20 '21 at 15:28