“This is the 18th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

We got the data from the network request in the last article, so we’ll use the network data to render the interface; In daily development, we first obtain data from the network, display a loading box in the process of obtaining data, and then render the interface after obtaining data, which is the business logic we often encounter; This can be done with Flutter via the StatefulWidget; Because this scenario is so common, Flutter provides two components, FutureBuilder and StreamBuilder, to quickly implement this function that requires asynchronous UI updates. Today we are going to learn how to use FlutterBuilder;

FutureBuilder

FutureBuilder in Flutter is defined as follows:

const FutureBuilder({
  Key? key,
  this.future,
  this.initialData,
  required this.builder,
})
Copy the code
  • future:FutureBuilderRely on theFuture, usually an asynchronous, time-consuming task;
  • initialData: Initial data, default data set by the user;
  • builder:WidgetConstructor, which will be inFutureThe different phases of execution are called multiple times and are signed as follows:
Widget Function(BuildContext context, AsyncSnapshot<T> snapshot)
Copy the code
  • snapshot: contains the status and result data of the current asynchronous task.
    • snapshot.connectionState: Gets the status information of asynchronous tasks.
    • snapshot.data: Obtains data information about asynchronous tasks.
    • snapshot.hasError: Checks whether the asynchronous task has error information.

In FutureBuilder, it relies on a Future and builds itself based on the state of the Future it relies on;

FutureBuilder is not very useful when there is too much data because we need to process it and save it;

The sample

Let’s look at the code:

FutureBuilder relies on the getConversationList method to build the UI.

It is called multiple times in different phases of the Future;

Render when there is no data, render a placeholder; Update the interface when data is available;

We can display different data according to the state:

ListTile

ListTile is another widget that Flutter provides. Let’s take a look at the final effect:

Operation effect:

  • titleHere we use to display the user name;
  • subtitle: we used to display the user’s latest message;
  • leading: We used to show the user’s avatar with rounded corners;
    • CircleAvatarisFlutterWe are provided with a special widget to display the use of circular head, the display effect is as follows: