Flutter ListView 不会在 setState 上更新
Flutter ListView doesn't update on setState
当我的 setState 在我的状态下运行时,我的颤振 ListView 没有更新 class。
是的,我的主要 class 是一个有状态的小部件,以防有人想知道
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() => new _MyAppState();
}
我的 setState 函数
setState(() {
if (price == "null") {
items.add("Item ${counter + 1}: error");
print("null");
} else {
items.add("Item ${counter + 1}: $price");
print("$price");
totalPrice += price;
}
counter++;
});
});
在我将 ListView 放入容器 -> 列 -> 展开之前,它工作正常。但是在我添加它之后,它在我的 setState 运行
时停止更新
body: new Container(
child: Column(
children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return Dismissible(
key: Key(item),
onDismissed: (direction) {
setState(() {
items.removeAt(index);
counter--;
});
Scaffold.of(context).showSnackBar(
SnackBar(content: Text("$item deleted")));
},
background: Container(color: Colors.red),
child: ListTile(title: Text('$item')),
);
},
),
),
谁能对 flutter 有更深入的了解,请教我这是怎么回事。我认为将 ListView 添加到容器中不会对其工作方式产生太大影响吗?
在 setstate 中进行计算不知何故导致了这个问题。相反,我在构建中进行了计算,因为我使用 setstate 仅添加到列表中。然后它将触发构建,其余的事情就在那里发生。这解决了我的问题
当我的 setState 在我的状态下运行时,我的颤振 ListView 没有更新 class。
是的,我的主要 class 是一个有状态的小部件,以防有人想知道
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() => new _MyAppState();
}
我的 setState 函数
setState(() {
if (price == "null") {
items.add("Item ${counter + 1}: error");
print("null");
} else {
items.add("Item ${counter + 1}: $price");
print("$price");
totalPrice += price;
}
counter++;
});
});
在我将 ListView 放入容器 -> 列 -> 展开之前,它工作正常。但是在我添加它之后,它在我的 setState 运行
时停止更新body: new Container(
child: Column(
children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return Dismissible(
key: Key(item),
onDismissed: (direction) {
setState(() {
items.removeAt(index);
counter--;
});
Scaffold.of(context).showSnackBar(
SnackBar(content: Text("$item deleted")));
},
background: Container(color: Colors.red),
child: ListTile(title: Text('$item')),
);
},
),
),
谁能对 flutter 有更深入的了解,请教我这是怎么回事。我认为将 ListView 添加到容器中不会对其工作方式产生太大影响吗?
在 setstate 中进行计算不知何故导致了这个问题。相反,我在构建中进行了计算,因为我使用 setstate 仅添加到列表中。然后它将触发构建,其余的事情就在那里发生。这解决了我的问题