【发布时间】:2019-02-03 11:38:24
【问题描述】:
我遇到了 Flutter 下拉菜单的问题。当我选择其中一项时,它会引发错误:
引发了另一个异常:'package:flutter/src/material/dropdown.dart':断言失败:第 481 行 pos 15:'value == null || items.where((DropdownMenuItem item) => item.value == value).length == 1': 不正确。
我在搜索,人们告诉我这个错误是因为所选元素不属于原始列表而产生的,但经过一些调试后我可以看到它确实如此。我找不到此错误的根源,因此我将不胜感激。
这是我的代码
FeedCategory 模型
import 'package:meta/meta.dart';
class FeedCategory {
static final dbId = "id";
static final dbName = "name";
int id;
String name;
FeedCategory({this.id, @required this.name});
FeedCategory.fromMap(Map<String, dynamic> map)
: this(
id: map[dbId],
name: map[dbName],
);
Map<String, dynamic> toMap() {
return {
dbId: id,
dbName: name,
};
}
@override
String toString() {
return 'FeedCategory{id: $id, name: $name}';
}
}
小部件
import 'package:app2date/repository/repository.dart';
import 'package:app2date/model/FeedSource.dart';
import 'package:app2date/model/FeedCategory.dart';
import 'package:app2date/util/ui.dart';
import 'package:flutter/material.dart';
class ManageFeedSource extends StatefulWidget {
ManageFeedSource({Key key, this.feedSource}) : super(key: key);
final FeedSource feedSource;
@override
_ManageFeedSource createState() => new _ManageFeedSource();
}
class _ManageFeedSource extends State<ManageFeedSource> {
FeedCategory _feedCategory;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('New Feed'),
),
body: new FutureBuilder(
future: Repository.get().getFeedCategories(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
List<FeedCategory> categoriesList = snapshot.data;
if (categoriesList != null) {
return new DropdownButton<FeedCategory>(
hint: Text('Choose category...'),
value: _feedCategory,
items: categoriesList.map((FeedCategory category) {
return DropdownMenuItem<FeedCategory>(
value: category,
child: Text(category.name),
);
}).toList(),
onChanged: (FeedCategory category) {
print('Selected: $category');
setState(() {
_feedCategory = category;
});
},
);
} else {
return Container(
decoration: new BoxDecoration(color: Colors.white),
);
}
},
),
);
}
@override
void initState() {
super.initState();
}
}
存储库 getFeedCategories 方法
Future<List<FeedCategory>> getFeedCategories() async {
return await database.getFeedCategories();
}
数据库 getFeedCategories 方法
Future<List<FeedCategory>> getFeedCategories() async {
var dbClient = await db;
var query = "SELECT * FROM $feedCategoryTableName;";
var result = await dbClient.rawQuery(query);
List<FeedCategory> feedCategories = [];
for (Map<String, dynamic> item in result) {
feedCategories.add(new FeedCategory.fromMap(item));
}
return feedCategories;
}
【问题讨论】:
-
所选项目需要是选择列表之一。
-
我一直在调试,选中的项目属于选择列表,可能是我误会了什么
-
您能否在遇到问题时添加您拥有的类别列表?这可能会有所帮助...
-
是的,我现在添加它
-
我添加了相关信息