gpt4 book ai didi

flutter - setState呈现后执行函数

转载 作者:行者123 更新时间:2023-12-03 03:57:23 30 4
gpt4 key购买 nike

在我的应用程序中,我想在添加项目后滚动到ListView的底部。
问题在于它在添加项目之前向下滚动,因此使一项隐藏。
呈现项目后,是否可以调用滚动功能?

示例代码:

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),
),
);
}
}

最佳答案

经过更多搜索后,我找到了答案:

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

资源:
https://stackoverflow.com/a/44142234/8722652

关于flutter - setState呈现后执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59923022/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com