Sohel Mahmud
Sohel Mahmud

Reputation: 185

convert List<object> in dart

I have a list of object:

  List<CartItemModel> cartItems;

my CartItemModel class is:

  class CartItemModel {
  String name, price, currency;
  int quantity;

  CartItemModel({
    this.name,
    this.price,
    this.quantity,
    this.currency = "GBP",
  });
}

Now i want to convert it to:

List items = [
  {
    "name": itemName,
    "quantity": quantity,
    "price": itemPrice,
    "currency": "GBP"
  },
  {
    "name": itemName,
    "quantity": quantity,
    "price": itemPrice,
    "currency": "GBP"
  }
];

Just simply assigning List items = cartItems; isn;t working.

Upvotes: 3

Views: 3347

Answers (5)

Ayad
Ayad

Reputation: 691

You should use a fromJson where you can pass the map as a JSON and it will give you back a list of your objects.

class CartItemModel {
  String name, price, currency;
  int quantity;

  CartItemModel({
    this.name,
    this.price,
    this.quantity,
    this.currency = "GBP",
  });

  CartItemModel.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        price = json['price'],
        currency = json['currency'],
        quantity = json['quantity'];
}

void main() {
  List<CartItemModel> items = [
    CartItemModel(
      currency: "GBP",
      quantity: 100,
      price: "200",
      name: "First name",
    ),
  ];

  print(items);

  List<CartItemModel> itemsFromJson = [
    {"name": "Second name", "quantity": 3, "price": "50", "currency": "GBP"},
    {"name": "third name", "quantity": 2, "price": "60", "currency": "GBP"}
  ].map((e) => CartItemModel.fromJson(e)).toList();
  
  print(itemsFromJson);
  print(itemsFromJson[0].name);
}

Upvotes: 0

J. S.
J. S.

Reputation: 9625

You can add a new constructor, specifically for Maps like JSON:

class CartItemModel {
  String name, price, currency;
  int quantity;

  CartItemModel({
    this.name,
    this.price,
    this.quantity,
    this.currency = "GBP",
  });

  /// New constructor
  CartItemModel.fromMap(Map map) :
      this.name = map['name'],
      this.price = map['price'],
      this.quantity = map['quantity'],
      this.currency = map['currency'];
}
items.forEach((item) {
  itemModelList.add(CartItemModel.fromMap(item));
})

Upvotes: 1

Ahmet KAYGISIZ
Ahmet KAYGISIZ

Reputation: 202

You can write toJSON and fromJSON manually in your class. Or you can use

dependencies: # Your other regular dependencies here
json_annotation: <latest_version>

dev_dependencies: # Your other dev_dependencies here build_runner: <latest_version> json_serializable: <latest_version>

You can look for details : https://flutter.dev/docs/development/data-and-backend/json

Upvotes: 0

BLKKKBVSIK
BLKKKBVSIK

Reputation: 3548

You may want to create a .toJson() method in your model.

Map<String, dynamic> _CartItemModelToJson(CartItemModel instance) => <String, dynamic>{
    'name': instance.itemName,
    'quantity': instance.quantity,
    'price': instance.itemPrice,
    'currency': instance.currency,
};

and convert your List<CartItemModel> to a Map with it.

Upvotes: 0

Moaid ALRazhy
Moaid ALRazhy

Reputation: 1744

try adding toJSON to your model .. this is complete example

import 'dart:convert';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Convert',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Convert Test'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<CartItemModel> cartItems = [CartItemModel(name: "name1", price: "price1", quantity: 1), CartItemModel(name: "name2", price: "price2", quantity: 2), CartItemModel(name: "name3", price: "price3", quantity: 3)];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
                onPressed: () {
                  List items = jsonDecode(jsonEncode(cartItems));
                  print(items);
                },
                child: Text("convert")),
          ],
        ),
      ),
    );
  }
}

class CartItemModel {
  String name, price, currency;
  int quantity;

  CartItemModel({
    this.name,
    this.price,
    this.quantity,
    this.currency = "GBP",
  });

  Map toJson() => {"name": name, "quantity": quantity, "price": price, "currency": "GBP"};
}

Upvotes: 2

Related Questions