Future<DropDownButton> 项为空/空/相同值 |扑
Posted
技术标签:
【中文标题】Future<DropDownButton> 项为空/空/相同值 |扑【英文标题】:Future<DropDownButton> items empty/null/same values | Flutter 【发布时间】:2021-11-09 13:02:42 【问题描述】:在我的网络应用程序的过程中,我希望用户允许进行更改并保存它们。对于该过程,我使用 SharedPreferences 来存储更改。我有一个名为 konzernDataTitle 的标题列表。通常,此列表用于显示我的标题。
为了更改某些内容,我编辑此列表并将其“上传”到我的 SharedPreferences。但是,一切正常,但我无法将新列表 prefsKonzernTitle 放入我的 DropDownButton。为此,我正在使用 FutureBuilder。错误很简单:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
[...]
The following assertion was thrown building FutureBuilder<List<DropdownMenuItem<String>>>(dirty,
state: _FutureBuilderState<List<DropdownMenuItem<String>>>#dcca3):
Assertion failed:
items == null || items.isEmpty || value == null ||
items.where((DropdownMenuItem<T> item)
return item.value == value;
).length == 1
"There should be exactly one item with [DropdownButton]'s value: MyTitle. \nEither zero or 2 or more
[DropdownMenuItem]s were detected with the same value"
The relevant error-causing widget was:
FutureBuilder<List<DropdownMenuItem<String>>>
FutureBuilder 功能:
Future<List<DropdownMenuItem<String>>> getDropDownItems() async
SharedPreferences prefs = await SharedPreferences.getInstance();
bool prefsTitleExist;
var newList = List<String>.empty();
if (prefs.containsKey("prefsKonzernTitle"))
var getPrefList = prefs.getStringList("prefsKonzernTitle");
newList = getPrefList!;
prefsTitleExist = true;
else
prefsTitleExist = false;
final actualList = prefsTitleExist ? newList : konzernDataTitle;
return actualList.map((data)
return DropdownMenuItem<String>(
value: data,
child: Text(
data,
),
);
).toList();
FutureBuilder 小部件
FutureBuilder<List<DropdownMenuItem<String>>>(
future: getDropDownItems(),
builder: (context, snapshot)
if (!snapshot.hasData)
return const SizedBox();
return DropdownButton<String>(
value: dropdownValue,
items: snapshot.data,
onChanged: (String? newValue)
setState(()
dropdownValue = newValue!;
i = konzernDataTitle.indexOf(newValue);
titleController.text = konzernDataTitle[i];
linkController.text = konzernDataLink[i];
imageController.text = konzernDataImage[i];
colorController.text =
konzernDataColor[i].toString();
);
,
);
),
我搜索了列表中的问题,但所有列表都是它们必须的样子。 所以也许你可以帮帮我。感谢您提供任何帮助。所有问题都会在几分钟内得到解答。
^蒂姆
【问题讨论】:
dropdownValue 的值是多少? 【参考方案1】:应该只有一项具有 [DropdownButton] 的值:MyTitle。 零个或 2 个或更多 检测到 [DropdownMenuItem]s 具有相同的值
上述错误表示dropdownValue
与下拉菜单项列表中的任何可用值或 dropMenuItemList 中存在的多个值都不匹配。
对于第一种情况,在初始化时设置dropdownValue = null
,对于第二种情况,检查菜单项没有重复。
【讨论】:
声明 dropdownValue 初始化为 null 时很简单。即String? dropdownValue = null;
我在你的代码sn-p中找不到初始化。以上是关于Future<DropDownButton> 项为空/空/相同值 |扑的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Flutter 中使用 Bloc 正确设置 DropdownButton 的值?
Dart / flutter:DropdownButton在值更改时导致异常
Flutter GetBuilder Dependent DropDownButton - 即使值已被重置,也应该只有一项具有 [DropdownButton] 的值