众所周知 在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));
})
效果:
我们并未刷新界面或者做别的操作 因此 又需要这种场景的 可以尝试使用