我是 Dart 和 Flutter 的新手,并尝试将新项目附加到我的 ListView。我创建了一个递增 this.value
的按钮,但没有任何反应。我是否错过了对 UI 的更新调用,这是否是正确的方法?
由于我将 ListView.builder
的值直接返回给 build
的调用者,因此我不确定如何获取列表以添加更多项目。非常感谢!
class MyList extends State<MyList> {
...
int value = 2;
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: this.value,
itemBuilder: (context, index) => this._buildRow(index)
);
TL;DR:调用 setState
是触发 UI 更新的正确方法吗?
最佳答案
调用 setState
是触发 UI 更新的正确方法。
来自docs :
Calling setState notifies the framework that the internal state of this object has changed in a way that might impact the user interface in this subtree, which causes the framework to schedule a build for this State object.
If you just change the state directly without calling setState, the framework might not schedule a build and the user interface for this subtree might not be updated to reflect the new state.
这里是一个 ListView
的小例子,它带有一个 Button
,可以向其附加项目。
import 'package:flutter/material.dart';
void main() => runApp(new MaterialApp(home: MyList()));
class MyList extends StatefulWidget {
@override
_MyListState createState() => _MyListState();
}
class _MyListState extends State<MyList> {
int value = 2;
_addItem() {
setState(() {
value = value + 1;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text("MyApp"),
),
body: ListView.builder(
itemCount: this.value,
itemBuilder: (context, index) => this._buildRow(index)),
floatingActionButton: FloatingActionButton(
onPressed: _addItem,
child: Icon(Icons.add),
),
);
}
_buildRow(int index) {
return Text("Item " + index.toString());
}
}
关于mobile - 将项目动态附加到 ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51343567/