dart - 获取 FutureBuilder 中 Future<Map<String,String>> 的值

标签 dart flutter

我有一个如下所示的 Future 方法:

Future<Map<String,String>> readFavorites() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    names = prefs.getKeys();
    for (var key in names) {
      debugPrint("key is " + key);
      debugPrint("value is " + prefs.get(key));
      pairs.putIfAbsent(key, () => prefs.get(key));
    }
    return pairs;
  }

我想在下面的 futurebuilder 中获取快照长度加上 map 的值:

 Widget build(BuildContext ctxt) {
    return Container(
      child: FutureBuilder(
        future: readFavorites(),
        builder: (context, AsyncSnapshot<Map<String,String>> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(
              //replace this with a loading icon
                child: new CircularProgressIndicator());
          } else {
            return ListView.builder(
                itemExtent: 90,
                itemCount: snapshot.data.length, <== How to get the map length? 
                itemBuilder: (BuildContext context, int index) {
                  return SingleDish(
                    dish_name: snapshot.data[index],
                    dish_picture: snapshot.data[index]., <== How to get the value from the map? 
                  );
                });
          }
        },
      ),
    );
  }

我尝试了以下但我得到了一个空异常:snapshot.data[snapshot.data[index]]。将不胜感激任何帮助。

更新

有趣的是,当我打印 key 时,我得到了以下信息:

lib_cached_image_data_last_clean

  Future<Map<String, String>> readFavorites() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    names = prefs.getKeys();
    //This  returned  the correct value because I hardcoded the key
    print("hardcoded key is " + prefs.getString("Cutlet"));
    for (var key in names) {
      //This fellow here returned lib_cached_image_data_last_clean
      print("key is" + key);
       pairs.putIfAbsent(key, () => prefs.get(key));
     // print("key is "  + pairs.length.toString());
    }
    return pairs;
  }

所以,我知道 readFavorites() 返回值这一事实。但不确定为什么 key 不是我在 SharedPreferences 中添加的。

最佳答案

看看这段代码,它是自动解释的,您可以根据自己的需要调整这段代码。

Widget build(BuildContext ctxt) {
    return Container(
      child: FutureBuilder(
        future: readFavorites(),
        builder: (context, AsyncSnapshot<Map<String,String>> snapshot) {
          switch( snapshot.connectionState){
            case ConnectionState.none:
              return Text("there is no connection");

            case ConnectionState.active:
            case ConnectionState.waiting:
              return Center( child: new CircularProgressIndicator());

            case ConnectionState.done:
              if (snapshot.data != null){
                Map<String,String> myMap = Map.from( snapshot.data ); // transform your snapshot data in map
                var keysList = myMap.keys.toList(); // getting all keys of your map into a list

                return ListView.builder(
                    itemExtent: 90,
                    itemCount: myMap.length, // getting map length you can use keyList.length too
                    itemBuilder: (BuildContext context, int index) {
                      return SingleDish(
                        dish_name: keysList[index], // key
                        dish_picture:  myMap[ keysList[index] ], // getting your map values from current key
                      );
                    }
                );
              }
              // here your snapshot data is null so SharedPreferences has no data...
              return Text("No data was loaded from SharedPreferences");
          }//end switch

        },
      ),
    );
  }

关于dart - 获取 FutureBuilder 中 Future<Map<String,String>> 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54531043/

相关文章:

flutter - Flutter : VS Code doesn't highlight compile time errors in test files

dart - flutter : Where is the title of Material App used?

flutter - 在Flutter中使用AlertDialog显示从数据库中选择的数据

flutter - 落在 pdf(EasyWebView) 顶部的窗口对话框 (showDatePicker) 的一部分不起作用,没有反应

dart - 我必须编译为JavaScript吗?

flutter - 潜在无限项目列表 : ListView. builder、StreamBuilder、FutureBuilder 还是其他?

flutter - 在 dispose 方法中获取提供者方法不起作用

dart - 将字符串从 firestore 保存到变量

dart - Flutter 突然无法将 apk 安装到真机

flutter - Flutter上的DatePicker:获取日期时为null: