将模型类放入列表

时间:2020-07-29 06:01:55

标签: flutter

我正在尝试对2个api端点进行2个数据响应。 1是单个响应,另一个是单个响应的数组。

尝试创建List/array版本时,出现错误。将以下模型类也添加到列表中的正确方法是什么?

class SingleDataResponse {
  final String id;
  final String title;

  SingleDataResponse({
    this.id,
    this.title
  });

  factory SingleDataResponse.fromJson(Map<String, dynamic> json) {
    return SingleDataResponse(
      id: json['id'],
      title: json['title']
    );
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['title'] = this.title;

    return data;
  }
}

这是我期望在List模型中得到的东西:

[{_id: "5f210afa8215ff24307c6c53", title: "Cool Title"}]

1 个答案:

答案 0 :(得分:0)

只要检查一下我创建的示例,是否可以回答您的问题就让我知道。

这是单个对象json

{
    "_id": "5f210afa8215ff24307c6c53",
    "title": "Cool Title"
}

这是对象列表:

[
    {
        "_id": "5f210afa8215ff24307c6c53",
        "title": "Cool Title"
    }
]

这是我在本地获取json的模型类。

// To parse this JSON data, do

import 'dart:convert';
// this is for single object
//     final dataModel = singledataModelFromJson(jsonString);

DataModel singledataModelFromJson(String str) =>
    DataModel.fromJson(json.decode(str));

String singledataModelToJson(DataModel data) => json.encode(data.toJson());

// this is for list of objects.
//     final dataModel = dataModelFromJson(jsonString);

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

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

class DataModel {
  DataModel({
    this.id,
    this.title,
  });

  String id;
  String title;

  factory DataModel.fromJson(Map<String, dynamic> json) => DataModel(
        id: json["_id"],
        title: json["title"],
      );

  Map<String, dynamic> toJson() => {
        "_id": id,
        "title": title,
      };
}

这是main中的逻辑:

import 'package:flutter/material.dart';
import 'package:json_parsing_example/models.dart';


void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: HomePage());
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  double value;
  @override
  void initState() {
    super.initState();
    getdata();
  }

  getdata() async {
    String data =
        await DefaultAssetBundle.of(context).loadString("json/parse.json");

    final singledataModel = singledataModelFromJson(data);
    print('single model');
    print(singledataModel.id);
    print(singledataModel.title);

    String listdata =
        await DefaultAssetBundle.of(context).loadString("json/parse2.json");

    List<DataModel> dataModel = dataModelFromJson(listdata);
    print(dataModel.length);
    print(dataModel[0].title);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: Text(''));
  }
}

只需检查一下,让我知道这是否是您想要的。