flutter - 如何在等待来自后端 API 的数据时最初显示 RefreshIndicator?

所以,我有这个“通知”屏幕,它为用户显示通知。导航到此屏幕时,它将是空白的,因为通知是从后端 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/

相关文章:

flutter - 如何在 Flutter 中使用音频播放器插件播放本地 mp3 文件

date - 如何在 flutter 中创建计时器选择器?

dart - 在 flutter 中使用底部导航栏在页面之间传递数据

dart - pubspec.yaml 中的配置标志如何工作?

flutter - 像 SliverAppBar 一样隐藏 TabBar

firebase - 如何通过与 Flutter Cloud Firestore 插件中的日期进行比

dart - 如何在 Flutter 中添加文件选择器插件?

dart - Flutter:如何获取文本行数

flutter - 展开 Flutter 中的应用栏以允许多行标题?

android-studio - flutter Android Studio : Error re