setState 只能更新当前widget的状态,当前widget下面还有别的widget情况下,是不会生效子widget
List<String> items = List.generate(10, (index) => "item$index");
class ChatList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
child: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ChatItem(chat: items[index]);
},
)
)]);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return ChatList();
}
void changeChatList(){
setState(){
items.add("new data")
}
}
}
这样在Hone Page调用chagngeChatList方法,ChatList中的视图没有变化,可以将items移动到HomePage,并将值通过构造传入,这种做法可以给变量提权
修改后
class ChatList extends StatelessWidget {
final List<String> items;
const ChatList({this.items})
@override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
child: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ChatItem(chat: items[index]);
},
)
)]);
}
}
class HomePage extends StatelessWidget {
List<String> items = List.generate(10, (index) => "item$index");
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return ChatList(items);
}
void changeChatList(){
setState(){
items.add("new data")
}
}
}
评论 (0)