首页 > 解决方案 > 如何使用共享首选项存储 3d 字符串数组

问题描述

我是 Flutter 的新手,正在做一些类似于日历的事情,其中​​所有用户创建的事件都存储在 3d arrayIventList[month][day][numOfIvent]中。我正在尝试将数组编码为字符串,以便通过共享首选项保存它,然后在使用jsonEncodeandjsonDecode方法接收数据时将其解码回来。但是在解码结果数组时,我得到error: The argument type 'String?' can't be assigned to the parameter type 'String'. (argument_type_not_assignable at [buzhigsr_app] lib \ calender.dart: 35). 也许有人知道如何解决这个错误或通过共享首选项保存数组?在此先感谢大家。

  List tList = List.generate(12, (m) => List.generate(31, (d) => List.generate(40, (i) => "")));
  getAndSendData() async{
  var prefs = await SharedPreferences.getInstance();
  prefs.setString('key', jsonEncode(tList));
  tList = jsonDecode(prefs.getString('key'));
  }

标签: flutterdartsharedpreferences

解决方案


prefs.setString('key', jsonEncode(tList)) 的类型是 String?。jsonDecode() 将 String 作为参数,所以当你给它 String? 时它会引发错误。您只需执行此操作即可检查它是否为空。

List<List<List<String>>> tList = List.generate(
        12, (m) => List.generate(31, (d) => List.generate(40, (i) => "")));
    getAndSendData() async {
      var prefs = await SharedPreferences.getInstance();
      prefs.setString('key', jsonEncode(tList));
      final listString = prefs.getString('key');
  

      if (listString != null) {
        final decodedList = jsonDecode(listString);
        if (listString != null) {
      final decodedList = jsonDecode(listString);
      final decodedTList = (decodedList as List)
          .map((firstD) => (firstD as List)
              .map((secondD) =>
                  (secondD as List).map((thirdD) => thirdD.toString()).toList())
              .toList())
          .toList();
      tList = decodedTList;
      }
    }

推荐阅读