【问题标题】:How to store a 3d array of strings using Shared preferences如何使用共享首选项存储 3d 字符串数组
【发布时间】:2021-11-08 05:53:53
【问题描述】:

我是 Flutter 的新手,正在做一些类似于日历的事情,其中​​所有用户创建的事件都存储在 3d 数组 IventList[month][day][numOfIvent] 中。我正在尝试将数组编码为字符串,以便通过共享首选项保存它,然后在使用jsonEncodejsonDecode 方法接收数据时将其解码回来。 但是在解码结果数组时,我得到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'));
  }

【问题讨论】:

    标签: flutter dart sharedpreferences


    【解决方案1】:

    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;
          }
        }
    

    【讨论】:

    • 非常感谢您的回答,问题已解决,但我想出了一个不同的问题。解码字符串时赋值失败,弹出错误:E/flutter(6216): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: type 'List ' is not a 'List >> ' 类型的子类型
    • 哦,是的,flutter 不确定 jsonDecode 输出是 3d 列表。您必须将 jsonDecode(listString) 分配给某个新变量并检查该变量是否为 3D 列表。这。您可以将其分配给 tList。
    • 问题是,当我检查 jsonDecode (listString) 或我将 jsonDecode (listString) 值传递给的新变量时,使用 .runtimeType 我将其作为 List 数据类型。这是否意味着在对数组进行编码后,它的类型发生了变化,还是我做错了什么?附言我的意思是通过检查 Flutter 认为 decodedList 是一个 List
    • 是的,你是对的,jsonDecode 不会反序列化嵌套数组(或对象)。我修复了手动反序列化的答案。更好的方法是将 3d 数组制作成模型并使用json_serializable 或类似的序列化和反序列化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 2012-08-22
    • 2017-07-02
    相关资源
    最近更新 更多