基础
FutureBuilder({
Key key,
this.future,
this.initialData,
@required this.builder,
})
FutureBuilder是一个StatefulWidget,组件会不会重绘看future是否有变化。如果我们不想让组件重绘,固定future
@override
void didUpdateWidget(FutureBuilder<T> oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.future != widget.future) {
if (_activeCallbackIdentity != null) {
_unsubscribe();
_snapshot = _snapshot.inState(ConnectionState.none);
}
_subscribe();
}
}
实例
- 第一,要使用混入AutomaticKeepAliveClientMixin,设置wantKeepAlive
- 第二,定义一个属性futrue只在initState中调用一次
- 第三,在build中使用,super.build(context);
class HomePage extends StatefulWidget{
@override
_HomePageState createState() => _HomePageState();
}
/// 与自定义的导航页面组件关联的状态子类
class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin{ //重要
Future<String> future;//重要
@override
bool get wantKeepAlive => true; //重要
@override
void initState() {
future = _getInitHttp(context); //避免不必要的ui重绘
super.initState();
}
@override
Widget build(BuildContext context) {
super.build(context); //重要
return FutureBuilder(
future: future,
builder: (BuildContext context, AsyncSnapshot snapshot){
//TODO
}
);
}
Future<String> _getInitHttp(BuildContext context) async {
//TODO
}
}