0

I am facing a problem i can't understand what's going wrong please help.

I saw this awnser but my problem doesn't solve. Flutter Json Encode List

here is json String: [{id: 4, quantity: 1, name: Implant, price: 7000}]

Services.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    quantity = json['quantity'];
    name = json['name'];
    price = json['price'];
  }

    print(_billModel.services);
    Iterable<dynamic> l = json.decode(_billModel.services.trim());

    var services = l.map((value) => Services.fromJson(value)).toList();
Naeem
  • 494
  • 1
  • 7
  • 25

1 Answers1

0

You need to add this keyword

    Services.fromJson(Map<String, dynamic> json) {
    this.id = json['id'];
    this.quantity = json['quantity'];
    this.name = json['name'];
    this.price = json['price'];
  }
    print(_billModel.services);
    Iterable<dynamic> l = json.decode(_billModel.services.trim());

    var services = l.map((value) => Services.fromJson(value)).toList();

You want to encode jsonstring then use the following method

 Map<String, dynamic> user = jsonDecode(jsonString);

print('Howdy, ${user['name']}!');
print('We sent the verification link to ${user['email']}.');

for inside models class

class User {
  final String name;
  final String email;

  User(this.name, this.email);

  User.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        email = json['email'];

  Map<String, dynamic> toJson() =>
    {
      'name': name,
      'email': email,
    };
}
  • A User.fromJson() constructor, for constructing a new User instance from a map structure.
  • A toJson() method, which converts a User instance into a map.

The responsibility of the decoding logic is now moved inside the model itself. With this new approach, you can decode a user easily.

Map userMap = jsonDecode(jsonString);
var user = User.fromJson(userMap);

print('Howdy, ${user.name}!');
print('We sent the verification link to ${user.email}.');

To encode a user, pass the User object to the jsonEncode() function. You don’t need to call the toJson() method, since jsonEncode() already does it for you.

String json = jsonEncode(user);

For more information , read this article from flutter.io

Scaphae Studio
  • 503
  • 3
  • 3