Flutter Future Builder

Published January 28, 2020

What are Future Operations?

Future operations is nothing but operations will take time to execute and return result in the future

 

So what we need to do in that time of execution?

We can overcome this problem by using asynchronous operations. To handle this operations we can use dart Async/await methods.

Will it possible to apply Asyn/await on widget?

To apply Async/await on widgets is tricky, to overcome this flutter introduced Future Builder widget.
Future builder will calls the future function to wait for the result, and as soon as it produces the result it calls the builder function where we build the widget

Flutter Future Builder

The Future builder result has AsyncSnapshot object

This AsyncSnapshot has 3 states

  • ConnectionState.none = In this state future is null.The AsyncSnapshot.data will be set to previous result persists or null.
  • ConnectionState.waiting = future is not null, but has not yet completed. The AsyncSnapshot.data will be set to initialData.
  • ConnectionState.done = future is not null, and has completed. If the future completed successfully

 

Sample of Future Builder

class FutureWidget extends StatefulWidget {
  String computeListOfTimestamps(int count) {
    StringBuffer sb = new StringBuffer();

    var random = Random();

    for (int i = 0; i < 2000; i++) {
      sb.writeln("Random Number : ${random.nextInt(2000)}");
      sb.writeln("");
    }
    return sb.toString();
  }

  Future<String> createFutureCalculation(int count) {
    return new Future(() {
      return computeListOfTimestamps(count);
    },);
  }

  @override
  FutureWidgetState createState() => new FutureWidgetState();
}

class FutureWidgetState extends State<FutureWidget> {
  bool _showCalculation = false;
  bool isLoading = false;
  GlobalKey<ScaffoldState>_scaffoldKey=GlobalKey();

  void _onInvokeFuturePressed() {
    setState(() {
      _showCalculation = !_showCalculation;
      isLoading=true;

    });
  }

  @override
  Widget build(BuildContext context) {
    Widget child = _showCalculation
        ? FutureBuilder(
            future: widget.createFutureCalculation(1000),

            builder: (BuildContext context, AsyncSnapshot snapshot) {
              return (snapshot.connectionState == ConnectionState.none &&
                  snapshot.hasData == null)?Container(child: Text("No Data"),):  Expanded(
                  child: SingleChildScrollView(
                      child: (snapshot.data == null)?Center(child: CircularProgressIndicator()):Text(
                          '${snapshot.data == null ? "" : snapshot.data}',
                          style: TextStyle(fontSize: 20.0))));
            })
        : Text('Press Refresh to load Data');
    return new Scaffold(
      key: _scaffoldKey,
      appBar: new AppBar(
        backgroundColor: Colors.pink,
        title: new Text("Future Builder "),
      ),
      body: new Center(
          child: new Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[child])),
      floatingActionButton: new FloatingActionButton(
        backgroundColor: Colors.pink,
        onPressed: _onInvokeFuturePressed,
        tooltip: 'Call Future',
        child: new Icon(Icons.refresh),
      ), // This trailing comma makes auto-formatting nicer for build
    );
  }
}

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1676 Views