带有浮动块的ScrollController

时间:2020-03-09 03:00:45

标签: flutter dart flutter-bloc

我上了这个课:

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 ,因为还没有附加的滚动视图。

有没有一种方法可以不使用延迟(使用延迟的声音听起来很hacke)?

1 个答案:

答案 0 :(得分:0)

好吧,我只是这样使用SchedulerBinding.instance.addPostFrameCallback

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

从flutter bloc here的github响应中得到了这一点。