2

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

1 Answer 1

1

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
  })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.