Flutter将JSON数组保存到SharedPreferences [英] Flutter Save JSON Array to SharedPreferences

查看:290
本文介绍了Flutter将JSON数组保存到SharedPreferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将JSON数组保存到SharedPreferences中?

How to save JSON array into SharedPreferences?

我尝试了以下类似的代码,但出现了一些错误: [ERROR:flutter/lib/ui/ui_dart_state.cc(148)]未处理的异常:类型'Text'不是其子类型输入字符串"

I've tried some code like this below, but i got some error : [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type 'Text' is not a subtype of type 'String'

```
for (var x = 0; x < dynamicwidget.length - 1; x++) {
  _listOrder={
    "id_product": dataJSON[x]["product_id"],
    "order_count": dynamicwidget[x].controller.text,
  };
}

String json = jsonEncode(_listOrder);

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(categoryname, json);

```

推荐答案

我建议您使用类似 (本地存储实现),用于保存和加载JSON.

I would recommend you to use something like this (local storage implementation) which is made for saving and loading JSON.

从代码片段本身中,我无法确切地告诉您是什么导致了此异常,但基本上到处都是期望出现String的地方,但是您提供了一个实际的Text小部件.它可能是categoryname变量.您从dynamicWidget实例中获得哪种controller?您确定controller.text返回String吗?

From the code snippet itself i can't tell you exactly what is causing this exception but basically everywhere a String is beeing expected but you provided an actual Text widget. It could be the categoryname variable. What kind of controller do you get from your dynamicWidget instance? Are you sure controller.text returns a String?

另一个注意事项:您将使用每个for循环重新分配_listOrder,而不是添加信息.您必须使用一个空的array,该空位将填充每个循环.

Another note: you are re-assigning _listOrder with every for loop instead of adding information. You have to use an empty array which will be filled with every loop.

这篇关于Flutter将JSON数组保存到SharedPreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆