我试图用来自宁静的api的数据填充flutter应用程序中的下拉按钮。但是我得到上面的错误。
这是我的模特;
class SavingsCategory extends Equatable{
final int id;
final String name;
SavingsCategory({
@required this.id,
@required this.name
});
@override
List<Object> get props => [name, id];
}
我的存储库正在获取数据
@override
Future<List<SavingsCategory>> getSavingsCategory()
async {
var token = await tokenRepository.getToken();
final response = await http.get(
'$baseUrl/user/savings-category',
headers: {HttpHeaders.authorizationHeader: 'Bearer $token'},
);
if (response.statusCode == 200) {
var data = json.decode(response.body);
List<SavingsCategory> categoryList = data['savingsCategory'].map<SavingsCategory>((json) {
return SavingsCategory.fromJson(json);
}).toList();
return categoryList;
} else {
throw new Exception("Couldn't get any saving categories");
}
}
我的集团代码
class SavingsCategoryBloc {
final repository = SavingsRepository();
final _savingsCategories = PublishSubject<List<SavingsCategory>>();
Stream<List<SavingsCategory>> get savingsCategories => _savingsCategories.stream;
fetchSavingsCategories() async {
final categories = await repository.getSavingsCategory();
_savingsCategories.sink.add(categories);
}
dispose(){
_savingsCategories.close();
}
}
最后是我的小部件
class _StartSavingPageState extends State<StartSavingPage> {
final SavingsCategoryBloc bloc = SavingsCategoryBloc();
@override
void initState() {
bloc.fetchSavingsCategories();
super.initState();
}
@override
Widget build(BuildContext context) {
....
Container(
padding: EdgeInsets.symmetric(
horizontal: 15.0, vertical: 10.0),
child: StreamBuilder<List<SavingsCategory>>(
stream: bloc.savingsCategories,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return DropdownButton<String>(
items: [
DropdownMenuItem<String>(
child: Text('No Savings Category'),
value: '',
),
],
onChanged: (String value) {
setState(() {
});
},
isExpanded: true,
hint: Text(
'SAVING FOR?',
style: TextStyle(
fontSize: 15.0, color: Colors.grey),
),
);
}
return DropdownButton(
value: category,
items: snapshot.data.map((category) {
DropdownMenuItem(
child: Text('${category.name}'),
value: category.id,
);
}).toList(),
onChanged: (value) {
setState(() {
category = value;
});
},
isExpanded: true,
hint: Text(
'SAVING FOR?',
style: TextStyle(
fontSize: 15.0, color: Colors.grey),
),
);
}),
),
}
}
如何解决此错误?我知道数据获取工作正常。我的窗口小部件肯定缺少某些内容。任何帮助将不胜感激。
答案 0 :(得分:0)
DropdownButton值必须在项目值中,或者必须为null。
DropdownButton(
value: categoryId,
items: snapshot.data.map((category) {
DropdownMenuItem(
child: Text('${category.name}'),
value: category.id,
);
}).toList(),
onChanged: (value) {
setState(() {
categoryId = value;
});
},
isExpanded: true,
hint: Text(
'SAVING FOR?',
style: TextStyle(
fontSize: 15.0, color: Colors.grey),
),
);