json - 如何使用 flutter 更新 json 数据

标签 json flutter

如何更新 JSON 值。我正在使用带有 REST API 的 flutter 来更改数据,但我正在努力如何刷新我的 JSON 数据对不起 friend 我对 flutter 不太了解所以请帮助我解决这个问题请在下面找到 JSON 的对象:

{
id: 1,
clef: "Y8F5eEo0",
IndiceSensibilite: "0.04",
Objectif: "1.00"
}

我想使用文本字段更新 IndiceSensibilite 的值。 我在这里是为了进一步澄清。 如果有人愿意帮助我,我将不胜感激。

最佳答案

您可以将 JSON 转换为对象,进行修改并返回 JSON:

import 'dart:convert'; // make sure you imported this library


String jsonValue = '{"id": 1, "clef": "Y8F5eEo0", "indiceSensibilite": "0.04", "objectif": "1.00" }'; // original JSON

使用 Future 将其转换为对象:

Future<ToObject> jsonToObject() async {
    var parse = json.decode(jsonValue);
    return ToObject.parseJson(parse);
}

您的对象(在我的例子中是 ToObject)将具有以下模型和方法:

class ToObject {
  int id;
  String clef;
  String indiceSensibilite;
  String objectif;

  ToObject({this.id, this.clef, this.indiceSensibilite, this.objectif});

  factory ToObject.parseJson(Map<String, dynamic> json) => ToObject(
      id: json['id'], clef: json['clef'], indiceSensibilite: json['indiceSensibilite'], objectif: json['objectif']);

  Map<String, dynamic> toJson() =>
      {'id': id, 'clef': clef, 'indiceSensibilite': indiceSensibilite, 'objectif': objectif};
}

我使用 FutureBuilder 获取数据,修改值并返回 JSON:

FutureBuilder<ToObject>(
     future: jsonToObject(),
     builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
              var object = snapshot.data;
              object.indiceSensibilite = "43.00";
              return Text(json.encode(object.toJson()));
          } else {
              return Text("Loading...");
          }
     },
)

您的最终结果是一个修改后的 JSON,您可以随意使用:

Modified JSON

关于json - 如何使用 flutter 更新 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56728335/

相关文章:

dart - 获取 Dart 类的名称作为 Type 或 String

dart - Flutter "showDialog"与 Navigator.pop()

flutter - 如何为 macos 桌面应用启用 Flutter 上网权限?

javascript - 在 Nativescript 中从本地 PC 加载 JSON 文件

json - Flask 前端具有 Tensorflow 但不具有 Tensorflow 服务

c# - 如何在 C# 中获取由解析器动态生成的 .json 文件的键和值

android - Dart :UI not found while trying to run . 飞镖文件

dart - 如何在 BLOC 的 Flutter 的 BottomNavigationBar 中设置 currentIndex?

javascript - 将 JSON 对象转换为新结构化 JSON 对象的最简单方法?

php - 数据未从 mysql json 数据类型返回