Inscription – sword tianya, start from your drip accumulation, and will keep improving, that is, toss every day.

支那 You might need
CSDN Netease Cloud classroom tutorial
The Denver nuggets EDU College Courses
zhihu Series of articles on Flutter

The FutureBuilder component can be used to display asynchronously loaded data updates to corresponding components of Flutter. The basic code is as follows:


/// The basic use of asynchronous loading components
class FutureBuilderPage extends StatefulWidget {
  @override
  _TestPageState createState(a) => _TestPageState();
}

/// The basic use of asynchronous loading components
class _TestPageState extends State {
  /// generics are asynchronously loaded data types
  /// Can be customized
  Future<String> _loadingFuture;

  @override
  void initState(a) {
    super.initState();
    _loadingFuture = loadingDataFunction();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Load data asynchronously"),),
      body: FutureBuilder<String>(
        // Future: This parameter requires a Future object, similar to network request, IO
        future: _loadingFuture,
        /// The data format here is the same as the generic format set by FutureBuilder above
        initialData: "Initialized data"./// The Widget displayed by the build calls back methods several times depending on the state of the load
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          // Check the loading status
          switch (snapshot.connectionState) {

            /// this can be interpreted as a callback to the start of asynchronous loading of the Widget displayed in the initial load
            case ConnectionState.none:
              return  Text('Result: ${snapshot.data}');

            /// callback in asynchronous loading
            case ConnectionState.active:
            case ConnectionState.waiting:
              return CircularProgressIndicator();

            // async load completed callback
            case ConnectionState.done:
              // Check whether loading failed
              if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              } else {
                /// use [snapshot.data] to get asynchronously loaded data
                return Text('Result: ${snapshot.data}'); }}return null; },),); }/// simulate a time-consuming network request
  Future<String> loadingDataFunction(a) async {
    / / / simulation
    await Future.delayed(Duration(milliseconds: 4000));

    return Future.value("Loading successful"); }}Copy the code

The running effect is as follows:

It is important to note that in order to prevent redrawing of FutureBuilder components, asynchronous loading loadingFuture needs to be defined separately, generally defined in the initialization function. Another way is to combine AsyncMemoizer asynchronous registers to ensure that asynchronous loading is only executed once

import 'package:async/async.dart' show AsyncMemoizer;
Copy the code

Then the corresponding usage code is as follows:


/// The basic use of asynchronous loading components
class FutureBuilderPage2 extends StatefulWidget {
  @override
  _TestPageState createState(a) => _TestPageState();
}

/// The basic use of asynchronous loading components
class _TestPageState extends State {

  // define the asynchronous register
  AsyncMemoizer _memoization = AsyncMemoizer<String>();
  /// simulate a time-consuming network request
  Future<String> loadingDataFunction(a) async {
    / / / simulation
    await Future.delayed(Duration(milliseconds: 4000));
    return Future.value("Loading successful");
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Load data asynchronously"),
      ),
      body: FutureBuilder<String>(
        // Future: This parameter requires a Future object, similar to network request, IO
        future: _memoization.runOnce(loadingDataFunction),
        /// The data format here is the same as the generic format set by FutureBuilder above
        initialData: "Initialized data"./// The Widget displayed by the build calls back methods several times depending on the state of the load
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          // Check the loading status
          switch (snapshot.connectionState) {

            /// this can be interpreted as a callback to the start of asynchronous loading of the Widget displayed in the initial load
            case ConnectionState.none:
              return Text('Result: ${snapshot.data}');

            /// callback in asynchronous loading
            case ConnectionState.active:
            case ConnectionState.waiting:
              return CircularProgressIndicator();

            // async load completed callback
            case ConnectionState.done:
              // Check whether loading failed
              if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              } else {
                /// use [snapshot.data] to get asynchronously loaded data
                return Text('Result: ${snapshot.data}'); }}return null; },),); }}Copy the code

The end