获取FutureBuilder中Future <map <string,string >>的值

时间:2019-02-05 09:18:39

标签: 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中获取快照长度以及地图的值:

 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]]。将不胜感激。

更新

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

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()返回值的事实。但是不确定为什么键不是我在SharedPreferences中添加的键。

1 个答案:

答案 0 :(得分:1)

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

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

        },
      ),
    );
  }