【问题标题】:parse json in object flutter在对象颤动中解析 json
【发布时间】:2020-01-25 20:45:38
【问题描述】:

我想在 Theme 对象中解析我的 json:

结果:

["[\"1\",\"Alternant\"]","[\"2\",\"DevOps\"]"]

方法getListTheme:

Future<List<String>> getListTheme() async {
    List<String> themes = List<String>();
    final SharedPreferences preferences = await SharedPreferences.getInstance();
    for (String key in preferences.getKeys()) {
      if (key == 'token') {
        preferences.containsKey(key);
      } else {
        themes.add(jsonEncode(preferences.getStringList(key)));
      }
    }
    return themes;
  }

其他代码:

await Theme().getListTheme().then((value){
      theme = jsonEncode(value);
    });

我的主题课:

class Theme {
  int id;
  String name;

  Theme({this.id, this.name});

  factory Theme.fromJson(Map<String, dynamic> json) {
    return Theme(
      id: json['id'],
      name: json['name'],
    );
  }
}

如何解析主题对象中的结果?

【问题讨论】:

  • 有问题吗?
  • ["[\"1\",\"Alternant\"]","[\"2\",\"DevOps\"]"] 我想用 id 在对象主题中解析这个/名称@AndresCastro

标签: android mobile flutter flutter-layout


【解决方案1】:

我猜你可以尝试像这样返回一个传递 JSON 的对象

Future<Theme> fechDataTheme(){

   Theme theme  =  Theme.fromJson('YOUR JSON HERE');

   return theme;

 }

一旦你有了对象,你就可以使用 FutureBuilder 在 UI 上获取它

FutureBuilder<Theme>(
        future: fetchDataTheme(),
        builder: (context, AsyncSnapshot snapshot) {


            if (snapshot.hasData) {
            return Column(

              children: <Widget>[
                Text(snapshot.data.id),
                Text(snapshot.data.name),
              ],

            );

【讨论】:

    【解决方案2】:

    我使用这个网站将 json 转换为 dart 对象 https://javiercbk.github.io/json_to_dart/

    【讨论】:

      猜你喜欢
      • 2021-09-25
      • 2020-08-14
      • 2019-08-31
      • 2019-11-08
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多