Future builder

A widget that builds itself according to the latest snapshot. I created a news app just to review how the future builder works. This is how I did it. Ensure that you utilise a stateful widget because its built to be able to change in its lifetime.

I removed the counter app code that comes default with every project created, then I added a tab controller function along with the TabBarView widget. I created new dart files to make models. These are classes that will carry the fields that I am expecting to get from my backend.

The code itself pretty much has 2 sections. The function that you call on the future field attribute of the builder, which retrieves the data from your backend. and the snapshot where you build up what to place on your display.

In my example below I used a switch case. While the data has not yet returned to the widget for display, I want a loading bar to be displayed. If the is an error, then rather that error should be displayed as a test. As soon as the data is ready to be displayed then the loading bar will be replaced with the data.



      child: FutureBuilder(
        future: _getNewsArticle(),
        builder: (BuildContext context, AsyncSnapshot snapshot){
          switch(snapshot.connectionState ){
            case ConnectionState.active:
              return _loading();
              break;
            case ConnectionState.waiting:
              return _loading();
              break;
            case ConnectionState.none:
            //error
              return _error("No connection has been made.");
              break;
            case ConnectionState.done:
            //complete
              if(snapshot.hasError){
                return _error(snapshot.error.toString());
              }
              if(snapshot.hasData){
                return _drawListOfNewsArticles(snapshot.data);
              }
              break;
          }
          return Container();
        },
      ),