Home > other >  How to apply automatic scrolling on Listview on Page Load in flutter
How to apply automatic scrolling on Listview on Page Load in flutter

Time:10-17

I want to apply automatic scrolling to this ListTile,

  Container(
                      height: 70,
                      width: double.maxFinite,
                      child: ListView.builder(
                        controller: _controller,
                        key: itemKey,
                        itemCount: 10,
                        itemBuilder: (BuildContext context, int index) {
                          return ListTile(
                            title: Text('demo ${index   1}'),
                          );
                        },
                      ),
                    ),

I declared this

  final itemKey = GlobalKey();
  final _controller = ScrollController();

And I placed this after widget build...

  if (_controller.hasClients) {
      _controller.animateTo(_controller.position.maxScrollExtent,
          duration: const Duration(milliseconds: 500), curve: Curves.easeInOut);
    }

CodePudding user response:

You can animate the list after first frame is build using addPostFrameCallback

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if (_controller.hasClients) {
        _controller.animateTo(_controller.position.maxScrollExtent,
            duration: const Duration(milliseconds: 500),
            curve: Curves.easeInOut);
      }
    });
  }
  • Related