首页 > 解决方案 > 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");
          }*/
        },
      ),

这是错误的演示(请注意,如果我返回菜单并返回搜索页面,复选框是如何消失的):

还要注意如果我单击搜索按钮,复选框是如何出现的

标签: android-studioflutterdart

解决方案


尝试将您更新的代码包装categoryMapsetState这样:

setState(() {
      for(int i = 0; i < newCategories.length; i++){
        categoryMap.putIfAbsent(newCategories[i]['name'].toString(), () => false);
      }
});

推荐阅读