2
votes

In my code, I want to show the floating action button based on condition. That condition is evaluated based on a HTTP call which is async in nature as per flutter. My below code is not returning anything.

 Widget _getFAB() {
    var Data = GetDetailsFromHTTP();

    userJSON.then((Data ) {
      if (1 == 2) {
        return Container();
      } else {
        return FloatingActionButton(
            backgroundColor: Colors.deepOrange[800],
            child: Icon(Icons.add_shopping_cart),
            onPressed: null);
      }
    });
  }

Await is also not working since it does not allow return type as widget. How to create a method which waits on async call and returns widget?

1
You might want to use FutureBuilder. - Ravinder Kumar

1 Answers

1
votes

You are using Async method in a not async method

Widget _getFAB() async {
  var Data = GetDetailsFromHTTP();

  return await userJSON.then((Data ) {
    if (1 == 2) {
      return Container();
    } else {
      return FloatingActionButton(
          backgroundColor: Colors.deepOrange[800],
          child: Icon(Icons.add_shopping_cart),
          onPressed: null);
    }
  });
}

Best way : prefer using a FutureBuilder, this is the purpose of this. https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

For exemple:

FutureBuilder<String>(
future: _calculation, // a previously-obtained Future<String> or null
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
  switch (snapshot.connectionState) {
    case ConnectionState.none:
      return Text('Press button to start.');
    case ConnectionState.active:
    case ConnectionState.waiting:
      return Text('Awaiting result...');
    case ConnectionState.done:
      if (snapshot.hasError)
        return Text('Error: ${snapshot.error}');
      return Text('Result: ${snapshot.data}');
  }
  return null; // unreachable
  })