【发布时间】:2018-10-27 07:23:00
【问题描述】:
我使用DropdownButton 和TextField 小部件编写了一个相当广泛的表单。这个概念是我有一个StatefulWidget,其中State<StatefulWidget> 的类包含2 个返回我想要构建的小部件的方法。通过这种方式,我可以轻松访问和使用输入的数据,并将其传递给一个函数来编写一封电子邮件。
但是,当我从选项中选择一个项目时,框架会在重建期间引发异常。我输入了一些日志函数,显示setState()方法成功将值保存到selectedValue变量中。
Widget buildMultiChoiceInputRow(var label, List<String> values) {
final List<String> options = values.toList();
selection = options.first;
final dropDownMenuOptions = options.map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList();
return new Column(
children: <Widget>[
new Row(
children: <Widget>[
new Expanded(
child: new Container(
padding:
const EdgeInsets.only(left: 5.0, top: 2.0, right: 5.0),
child: new Text(label, style: commonInfoCardInfoTextBlack16Bold)),
),
],
),
new Row(
children: <Widget>[
new Expanded(
child: new Container(
padding: const EdgeInsets.only(left: 5.0, right: 5.0),
child: new DropdownButton(
value: selectedValue,
items: dropDownMenuOptions,
onChanged: (selection) {
setState(() {
selectedValue = selection;
switch (label) {
case labelVirtualAdoption:
tempAdoptionType =
composeMultiChoiceAnswer(label, selection);
print(selection);
print(selectedValue);
break;
case labelAskedAboutSpecies:
tempAskedAboutSpecies =
composeMultiChoiceAnswer(label, selection);
break;
case labelHouseOrFlat:
tempHouseOrFlat =
composeMultiChoiceAnswer(label, selection);
break;
....
default:
break;
}
});
}),
),
)
],
),
new Divider(color: Colors.transparent)
],
);
}
这是一个例外:
I/flutter (20998): The following assertion was thrown building AdoptionInput(dirty, state: AdoptionInputState#3cc80):
I/flutter (20998): 'package:flutter/src/material/dropdown.dart': Failed assertion: line 481 pos 15: 'value == null ||
I/flutter (20998): items.where((DropdownMenuItem<T> item) => item.value == value).length == 1': is not true.
这里是堆栈,显示在重建期间抛出了异常:
I/flutter (20998): #2 new DropdownButton (package:flutter/src/material/dropdown.dart)
I/flutter (20998): #3 AdoptionInputState.buildMultiChoiceInputRow (package:osszefogasaszanhuzokert/adoptionPageUtilities.dart:443:28)
I/flutter (20998): #4 AdoptionInputState.build (package:osszefogasaszanhuzokert/adoptionPageUtilities.dart:639:11)
I/flutter (20998): #5 StatefulElement.build (package:flutter/src/widgets/framework.dart:3730:27)
I/flutter (20998): #6 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3642:15)
I/flutter (20998): #7 Element.rebuild (package:flutter/src/widgets/framework.dart:3495:5)
I/flutter (20998): #8 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2242:33)
问题似乎与a former bug in flutter 非常相似,但是如果我尝试在initState() 中初始化selection 和selectedValue,则会在第一次构建表单时抛出相同的异常。
我在这里错过了什么?
【问题讨论】:
-
与此同时,我发现当构建具有与“igen”“nem”不同的值(或者我认为与我使用的第一个不同)的小部件时会引发异常