所以,我有这个“通知”屏幕,它为用户显示通知。导航到此屏幕时,它将是空白的,因为通知是从后端 API 实时加载的。
这里有一些代码来说明问题:
class _MyItemsPageState extends State<MyItemsPage> {
final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
new GlobalKey<RefreshIndicatorState>();
List<MyItem> _items = [];
@override
void initState() {
super.initState();
// Nothing is displaying on screen initially, since the items are loaded from API on startup.
// Preferably in this state, the refresh indicator would be shown while the items load.
// It's not currently possible in this place, since it seems that the Widget hasn't been built yet.
_refreshIndicatorKey.currentState.show(); // currentState null at this time, so the app crashes.
_loadItems();
}
// (unrelated code removed)
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new RefreshIndicator(
key: _refreshIndicatorKey,
onRefresh: _loadItems,
child: new ListView(
padding: new EdgeInsets.symmetric(vertical: 8.0),
children: _buildItemWidgets(),
),
),
);
}
}
问题是 _refreshIndicator.currentState 在调用 initState() 函数时为空,因为 Widget 尚未构建。
在这种情况下,在 RefreshIndicator 上调用 show() 的正确位置是什么?
最佳答案
我认为最好的选择是使用 https://docs.flutter.io/flutter/scheduler/SchedulerBinding/addPostFrameCallback.html 安排 _refreshIndicatorKey.currentState.show()
这样,当小部件完成构建时,调用 show() 方法是安全的,并且不依赖于 Future 中的固定时间。
这里是例子:
void initState() {
super.initState();
SchedulerBinding.instance.addPostFrameCallback((_){ _refreshIndicatorKey.currentState?.show(); } );
}
但是,毫无疑问,我确实认为小部件本身可以有一个额外的参数来允许开箱即用。
https://stackoverflow.com/questions/44031454/