Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute function after setState has rendered

Tags:

flutter

dart

In my App, I want to scroll to the bottom of a ListView after adding an Item. The problem is that it scrolls down before adding the Item and therefore leaves one item hidden. Is there a way to call the scroll function after the item has rendered?

Example code:

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var _items = [];
  var _counter = 0;

  final _listViewController = ScrollController();

  void _addItem() {
    setState(() {
      _items.add(++_counter);
    });
    _listViewController.jumpTo(_listViewController.position.maxScrollExtent);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Demo'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(16.0),
        controller: _listViewController,
        children: [
          ..._items.map((i) => ListTile(title: Text(i.toString()))),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addItem,
        child: Icon(Icons.add),
      ),
    );
  }
}
like image 312
FA_developes Avatar asked Jul 27 '26 12:07

FA_developes


1 Answers

After some more searching, I found the answer:

void _addItem() {
   setState(() {
     _items.add(++_counter);
   });
   SchedulerBinding.instance.addPostFrameCallback((_) {
     _listViewController.jumpTo(_listViewController.position.maxScrollExtent);
   });
}

Source: https://stackoverflow.com/a/44142234/8722652

like image 118
FA_developes Avatar answered Jul 29 '26 05:07

FA_developes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!