0

how to update JSON value. I am using flutter with a REST API to change the data but I'm struggling how to refresh my JSON data sorry friends I don't know much about the flutter so please help me out about it please find JSON'S Object below:

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

I want to update the value of IndiceSensibilite using a textField. I m here for more clarification. i will be very thankful if there's someone who gonna help me.

1 Answer 1

2

You can transform the JSON into an Object, make your modifications and back to JSON:

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


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

Use a Future to convert it into Object:

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

and your Object (ToObject in my case) will have the following model and methods:

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

I used a FutureBuilder to get the data, modify the value and back to 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...");
          }
     },
)

Your end result is a modified JSON to use as you wish:

Modified JSON

Sign up to request clarification or add additional context in comments.

2 Comments

my pleasure! happy to know that's what you needed.
If I have a set of model and just want to update only certain part, how does it work??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.