【问题标题】:Flutter how to convert a string to list using json decode in dartFlutter 如何在 dart 中使用 json decode 将字符串转换为列表
【发布时间】:2021-05-01 16:11:02
【问题描述】:

我有下面的列表,我想将其转换并存储为字符串,以便以后需要它时,我会将字符串解码回列表,以便将其用作参数。

 List allTasks = [
   {"project-name":"My First Project"},
   {"date-time":"12 Mar 2021Z 12:34:05 am"},
   {"people":["John","Doe"]},
   {"project-body":[
    {
     "id":"0",
     "color": Colors.transparent,
     "name":"hello amigo",
     "sub-children":[
       {
        "id":"0",
        "color": Colors.transparent,
        "type":"text",
        "state":"waiting",    
        "mediaUrl":"",             
         "name":"Heya its me",
         "hasMessage":false,
         "people":[
           {"person-id":"id110",
            "profile-pic":"",
           }
         ]
       },       
     ],
    },     
   ],
  }
 ];

此代码用于将其存储在 sharedPreference 中首先我将列表转换为字符串,然后传递它。

  void storeValuesLocally(String mainlist)async{
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String myToJson = json.encode(mainlist);
  await prefs.setString('main-list', myToJson);  
  }

下面我正在尝试将字符串解码回列表

  void getAndSetTaskValues()async{
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String values = (prefs.getString('main-list') ?? [].toString());
  var castedToList = json.decode(values);
    print(castedToList[0].runtimeType); // String
  }

我的问题 每当我尝试将解码结果分配给列表时,它都会引发错误。这是因为castedToList 是一个字符串,因为当我检查类型时它是一个字符串。 我该如何解决这个问题。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    不要将其转换为字符串然后对其进行编码。因为解码它会返回一个字符串,就像现在发生在你身上一样。

    相反,按原样对列表进行编码。

    void storeValuesLocally(List mainlist)
    

    【讨论】:

    • 共享首选项不能存储List
    【解决方案2】:

    我发现问题在于, Colors.transparent 不是 json 类型,因此无法编码或解码。

    【讨论】:

      猜你喜欢
      • 2022-12-19
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      • 2022-11-07
      相关资源
      最近更新 更多