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();

1 Answer 1

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

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

1 Comment

hope you find the edited one usefull. if not let me know

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.