checkbox - SetState() 在构造函数中调用
问题描述
我已经建立了一个自定义列表。现在我包含一个复选框,如果我要选中或未选中,则会引发以下错误:'setState() called in constructor'
class Lists extends StatefulWidget{
@override
_List createState() => _List();
}
class _List extends State<Lists> {
bool checkedvalue = true;
@override
Widget build(BuildContext context) {
return futureBuilder();
}
Widget futureBuilder(){
var futureBuilder = new FutureBuilder(
future: rest.fetchPost(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return new Text('loading...');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return listBuilder(context, snapshot);
}
}
);
return new Scaffold(
body: futureBuilder,
);
}
Widget listBuilder(BuildContext context, AsyncSnapshot snapshot) {
List<rest.Status> values = snapshot.data;
if (values == null || values.length == 0){
return null;
}
int items = values.length;
return ListView.builder(
itemCount: items,
itemBuilder: (BuildContext context, int index) {
String statusText;
Image image ;
Uint8List bytes;
if(statusList.globalStatus != null){
for(int i=0;i< statusList.globalStatus.length; i++){
if(values[index].statusID == statusList.globalStatus[i].id){
if(statusList.globalStatus[i].kurzform != null){
statusText = statusList.globalStatus[i].kurzform;
}else{
statusText = statusList.globalStatus[i].kurzform;
}
if (statusList.globalStatus[i].icon != null){
bytes = base64Decode(statusList.globalStatus[i].icon);
image = new Image.memory(bytes) ;
}
}
if(image== null || statusText == null){
statusText= 'Kein Status';
image= new Image.asset('assets/null.png');
}
}
}
return new Container(
decoration: new BoxDecoration(
border: Border(top: BorderSide(
color: Colors.black26,
width: 1
)
)
),
child:Column(
children: <Widget>[
CustomListItemTwo(
statusText: statusText,
status:image,
materialNR: values[index].uArtText,
material: values[index].untersuchungsMaterialName,
probenArt: values[index].probenart,
eingansdatum: values[index].eingangsdatumText,
patient: values[index].vorname + ' ' + values[index].nachname ,
geburtsdatum: values[index].geburtstagText ,
),
Checkbox(
value: checkedvalue ,
onChanged: (bool newValue) =>
setState(() {
checkedvalue = newValue;
})
),
]
),
);
}
);
}
}
我/颤振(5067):══╡手势发现异常╞════════════════════════════════════════════ ════════════════════════════════ I/flutter(5067):处理手势时抛出以下断言:I /flutter ( 5067): setState() 在构造函数中调用: _List#9044e(lifecycle state: created, no widget, notmounted) I/flutter ( 5067): 当你在一个状态对象上为一个小部件调用 setState() 时会发生这种情况尚未插入到 I/flutter ( 5067): 小部件树。没有必要在构造函数中调用 setState(),因为状态是 I/flutter ( 5067):在最初创建时已经假定它是脏的。
解决方案
我下面的代码不是 testet。
您的代码中存在一些概念错误。你不应该在你的构建方法中获取任何东西!
如果你在你的 build-method 中添加一个 print 例如“building...”(就像我在下面所做的那样),你就会明白为什么。build 方法被调用的次数比你想象的要多。因此,您正在调用 WebService 或不止一次,响应将不止一次。实际上该setState()
方法将触发构建。
如果您想在开始时拉一些东西,请使用该initState()
方法。该方法将在状态创建时调用一次。将变量用于调用状态并在构建方法中对其做出反应(如前所述setState()
将触发重建)。
我稍微重构了你的代码,考虑到这个概念,你的开关/复选框问题可能会消失。
另请查看如何使用 Futures https://api.flutter.dev/flutter/dart-async/Future-class.html
class Lists extends StatefulWidget {
@override
_List createState() => _List();
}
class _List extends State<Lists> {
bool checkedvalue = true;
bool loading = true;
AsyncSnapshot asyncSnapshot = null;
@override
void initState() {
futureBuilder();
super.initState();
}
@override
Widget build(BuildContext context) {
print("building...");
if(asyncSnapshot != null && asyncSnapshot.hasError){
return Text("Error : ${asyncSnapshot.error}");
}
return (loading) ? Text("LOADING") : listBuilder(context, asyncSnapshot);
}
void futureBuilder() async {
rest.fetchPost().then((snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
setState(() {
loading = true;
});
break;
default:
if (snapshot.hasError) {
setState(() {
loading = false;
});
} else {
setState(() {
loading = false;
asyncSnapshot = snapshot;
});
}
}
});
}
.....
推荐阅读
- widget - 无法在 iOS 14 模拟器中启动主屏幕小部件
- python - TF2 - 拆分输入数据并使用不同的预训练层权重
- prisma - 实体货币交易架构设计
- html - 如何在 React 中为 div 添加 css?
- r - 使用 monocle3 组合 cell_data_sets
- ubuntu - microk8s,DEVOPS:无法连接到服务器:x509:证书对
, 不是 - vba - 在 MSGraph 图表对象上使用后期绑定
- node.js - 如何通过 dialogflow API 服务将请求标头从集成传递到我的 webhook 服务?
- java - 将 SPRING 的版本更改为 2.3.0 后,无法使用 javax.xml.bind.JAXBContext 解组文件
- ibm-mq - IBM MQ 身份验证