FutureBuilder在實際中的應用

衆所周知 在flutter中有兩種狀態的widget :

StatelessWidget 和  StatefulWidget
在實際開發中一般爲了方便 我們都常用StatefulWidget 因爲一般開發過程中 需要經常變動界面 涉及到變化 但是是不是StatelessWidget就一定不可變呢
我們來討論下  FutureBuilder 
字面意思很明顯 官方文檔 也很明顯
  /// Creates a widget that builds itself based on the latest snapshot of
  /// interaction with a [Future].
  ///
  /// The [builder] must not be null.

我們來試驗一下如下代碼:

FutureBuilder(
            future: Future.delayed(
                Duration(seconds: 2), () => 100), //throw('error msg')
            initialData: 10,
            builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
              print(snapshot.connectionState);
              if (snapshot.hasError) {
                return Text('error');
              }
              return Text(
                '${snapshot.data}',
                style: TextStyle(fontSize: 30),
              );
            })

控制檯輸出

即當前的snapshot.connectionState 狀態有兩種 等待狀態 和 執行完畢狀態

可以看到 由初始值10 變成了我們的最終值100

當然error也是可以的

以下代碼

FutureBuilder(
            future: Future.delayed(Duration(seconds: 2),
                () => throw ('error msg')), //throw('error msg')
            initialData: 10,
            builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
              print(snapshot.connectionState);
              if (snapshot.hasError) {
                return Text('error',
                    style: TextStyle(fontSize: 30, color: Colors.red));
              }
              return Text('${snapshot.data}', style: TextStyle(fontSize: 30));
            })

 

效果:
我們並未刷新界面或者做別的操作 因此 又需要這種場景的 可以嘗試使用 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章