android-studio - Dart - 除非刷新,否则使用列表视图动态创建复选框为空白
问题描述
我正在尝试使用 ListView 动态创建复选框。如果我重新启动模拟器并转到我的搜索页面,则复选框不存在。如果我“热重载”模拟器(ctrl + S),则会出现复选框。如果我返回菜单并返回搜索页面,复选框就会消失。如果我点击“搜索”在我的数据库中搜索食谱,复选框会重新出现。我不知道这里发生了什么。
这是我的分类图:
Map<String, bool> categoryMap = {};
var checkedCategories = [];
void findCategories() async {
int responseCode = await categories();
print(responseCode);
if(responseCode == 200){
newCategories = categoriesList;
for(int i = 0; i < newCategories.length; i++){
categoryMap.putIfAbsent(newCategories[i]['name'].toString(), () => false);
}
print("new categories of length ${newCategories.length} are: " + newCategories[1]['name'].toString());
print("categoryMap is: " + categoryMap.toString());
} else {
print("Error: unauthorized");
}
}
getCheckedCategories(){
categoryMap.forEach((key, value) {
if(value == true)
{
checkedCategories.add(key);
}
});
// Printing all selected items on Terminal screen.
print(checkedCategories);
print(categoryMap.keys);
// Here you will get all your selected Checkbox items.
// Clear array after use.
checkedCategories.clear();
}
@override
void initState() {
super.initState();
findCategories();
print('hi there');
}
这是我试图显示复选框的地方:
child: Column(
children: [
SizedBox(height: 40.0,),
new ListView(
scrollDirection: Axis.vertical,
shrinkWrap: true,
children: categoryMap.keys.map((String key) {
//print("here is a new checkbox!");
return new CheckboxListTile(
title: new Text(key),
value: categoryMap[key],
activeColor: Colors.pink,
checkColor: Colors.white,
onChanged: (bool value) {
setState(() {
categoryMap[key] = value;
});
},
);
}).toList(),
),
isLoading ? Center(
child: CircularProgressIndicator(),
) : new RaisedButton(
child: Text('Search'),
color: Colors.orange[600],
textColor: Colors.white,
onPressed: () async {
setState(() {
isLoading = true; //Data is loading
});
/*int response_code = await categories();
print(response_code);*/
clearResults();
await getRecipe(searchController.text);
Navigator.push(context, MaterialPageRoute(builder: (context)=>RecipeResultsPage()));
/*if(response_code == 200){
await getRecipe(searchController.text);
Navigator.push(context, MaterialPageRoute(builder: (context)=>RecipeResultsPage()));
} else {
print("Error: unauthorized");
}*/
},
),
这是错误的演示(请注意,如果我返回菜单并返回搜索页面,复选框是如何消失的):
解决方案
尝试将您更新的代码包装categoryMap
成setState
这样:
setState(() {
for(int i = 0; i < newCategories.length; i++){
categoryMap.putIfAbsent(newCategories[i]['name'].toString(), () => false);
}
});
推荐阅读
- c# - 从 VS 2019 C# 连接时,Microsoft Azure Sql 连接速度很慢
- xcode - 核心数据中的照片采集
- python - 无需使用 json 文件即可访问 Google API
- shopware - 促销台用品专列6
- javascript - 运行 hashcat 或 john the ripper 的 Web 应用程序
- jmeter - JMeter 可以记录来自 .razor 页面的捕获请求吗?
- sql - T-sql count 每周对具有日期间隔的行的次数
- node.js - Stripe - 如何使用帐户电子邮件和帐单电子邮件创建客户?
- android - 如何测试 androidx (proto) 数据存储,java.lang.ExceptionInInitializerError
- java - java - 如何使用java中的2个线程在文件中打印数据