0

我有这堂课:

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总是返回false 。

有一种不使用延迟的方法(使用延迟听起来很糟糕)?

4

1 回答 1

1

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

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

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

于 2020-03-09T17:09:12.323 回答