Home > Software design >  Search if exists on local JSON and show new value flutter
Search if exists on local JSON and show new value flutter

Time:07-08

I have a code that looks like this

aa.json

[  {
    "old_value": "992812738823",
    "new_value": "4661"
  },
  {
    "old_value": "992112734423",
    "new_value": "9901"
  }]


    final String response = await rootBundle.loadString('assets/json/aa.json');
    

    var json = jsonDecode(response) as Map;



      if (json.containsValue(scanResult)) { //scanResult example = 992812738823
        print('has the value');
        print('The new value is: $json['new_value']'); 
      } else {
        print('no value');

      }
/*

scanResult is getted random from an item as a string.

But I'm having hard time displaying only the info that I want.

CodePudding user response:

You can use below code for parsing your json.

final welcome = welcomeFromJson(jsonString);

// To parse this JSON data, do
//
//     final welcome = welcomeFromJson(jsonString);

import 'dart:convert';

List<Welcome> welcomeFromJson(String str) => List<Welcome>.from(json.decode(str).map((x) => Welcome.fromJson(x)));

String welcomeToJson(List<Welcome> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Welcome {
    Welcome({
        this.oldValue,
        this.newValue,
    });

    String oldValue;
    String newValue;

    factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
        oldValue: json["old_value"],
        newValue: json["new_value"],
    );

    Map<String, dynamic> toJson() => {
        "old_value": oldValue,
        "new_value": newValue,
    };
}

  • Related