ScrollController with flutter bloc

Issue

I have this 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();
  }
}

Basically, what I want is to scroll the listview when new item is added, however, sc.hasClients always returns false since there’s no attached scroll views yet.

There’s a way to this without using delay (using delay sounds hacky e.e)?

Solution

Ok, I just used SchedulerBinding.instance.addPostFrameCallback, like this:

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

Got this from a response at github of flutter bloc, here.

Answered By – Kiritonito

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *