简体   繁体   English

转换列表<object>在 dart<div id="text_translate"><p> 我有一个 object 的列表:</p><pre> List&lt;CartItemModel&gt; cartItems;</pre><p> 我的CartItemModel class 是:</p><pre> class CartItemModel { String name, price, currency; int quantity; CartItemModel({ this.name, this.price, this.quantity, this.currency = "GBP", }); }</pre><p> 现在我想将其转换为:</p><pre> List items = [ { "name": itemName, "quantity": quantity, "price": itemPrice, "currency": "GBP" }, { "name": itemName, "quantity": quantity, "price": itemPrice, "currency": "GBP" } ];</pre><p> 只需简单地分配List items = cartItems; 不工作。</p></div></object>

[英]convert List<object> in dart

I have a list of object:我有一个 object 的列表:

  List<CartItemModel> cartItems;

my CartItemModel class is:我的CartItemModel class 是:

  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;只需简单地分配List items = cartItems; isn;t working.不工作。

try adding toJSON to your model.. this is complete example尝试将 toJSON 添加到您的 model .. 这是完整的示例

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

You may want to create a .toJson() method in your model.您可能想在 model 中创建一个.toJson()方法。

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.并将您的List<CartItemModel>转换为Map

You can write toJSON and fromJSON manually in your class.您可以在 class 中手动写入 toJSON 和 fromJSON。 Or you can use或者你可以使用

dependencies: # Your other regular dependencies here dependencies: # 你的其他常规依赖项
json_annotation: <latest_version> json_annotation: <最新版本>

dev_dependencies: # Your other dev_dependencies here build_runner: <latest_version> json_serializable: <latest_version> dev_dependencies: # 你的其他 dev_dependencies build_runner: <latest_version> json_serializable: <latest_version>

You can look for details: https://flutter.dev/docs/development/data-and-backend/json可以查看详情: https://flutter.dev/docs/development/data-and-backend/json

You can add a new constructor, specifically for Maps like JSON:您可以添加一个新的构造函数,专门用于 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));
})

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.您应该使用 fromJson ,您可以在其中将 map 作为 JSON 传递,它会给您返回对象列表。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM