带有 flutter bloc 的 ScrollController

ScrollController with flutter bloc

我有这个class:

class MyView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      title: Text("My Page"),
      body: BlocProvider<MyBloc>(
        builder: (context) => MyBloc()..add(OnOpen()),
        child: BlocBuilder<MyBloc, MyBlocState>(
          builder: (context, state) => _buildView(state, context)
        )
      )
      ...
    );
  }

  Widget _buildView(MyBlocState state, BuildContext context) {
    if (state is MainState) {
      ScrollController sc = ScrollController(
        initialScrollOffset: 0,
        keepScrollOffset: true
      );

      ListView lv = ListView.separated(
        controller: sc,
        scrollDirection: Axis.horizontal,
        ...
      );

      if (state.hasNewItem && sc.hasClients) {
        sc.animateTo(
          ...
        );
      }

      return lv;
    }

    return _loadingScreen();
  }
}

基本上,我想要的是在添加新项目时滚动列表视图,但是,sc.hasClients 总是 returns false 因为没有附加的滚动观看次数。

有没有使用延迟的方法(使用延迟听起来很老套 e.e)?

好的,我刚用了SchedulerBinding.instance.addPostFrameCallback,像这样:

if (state.hasNewItem) {
  SchedulerBinding.instance.addPostFrameCallback((_) {
    sc.animateTo(
      ...
    );
  });
}

从 flutter bloc github 的回复中得到这个,here