我想转换json到一个兼容的dart格式帮助我我是初学者在扑

lbsnaicq  于 2023-09-28  发布在  其他
关注(0)|答案(1)|浏览(70)

我正在学习flutter & dart,我试图在练习中实现状态管理和REST API数据,但我从2天开始就遇到了同样的错误。我的过程是相同的tutorail tutorial link,但我得到了一个错误的地方有我的数据服务

import 'dart:convert';

import 'package:flutter_cubit/model/data_model.dart';
import 'package:http/http.dart' as http;

class DataServices {
  String baseUrl = "https://61f969ae69307000176f7243.mockapi.io";
  Future<List> getInfo() async {
    var apiUrl = '/DevMobile';
    http.Response res = await http.get(Uri.parse(baseUrl + apiUrl));

    try {
      if (res.statusCode == 200) {
        List<dynamic> list = json.decode(res.body);
        print('donnees service non formaté $list');
        return list.map((e) => DataModel.fromJson(e)).toList();
      } else {
        return <DataModel>[];
      }
    } catch (e) {
      //print(e);
      return <DataModel>[];
    }
  }
}

和数据模型

class DataModel {
  String name;
  String img;
  int price;
  int people;
  int stars;
  String description;
  String location;
  dynamic createdAt;

  DataModel({
    required this.name,
    required this.img,
    required this.price,
    required this.people,
    required this.stars,
    required this.description,
    required this.location,
  });

  factory DataModel.fromJson(Map<String, dynamic> json) {
    return DataModel(
      name: json["name"],
      img: json["img"],
      price: json["price"],
      people: json["people"],
      stars: json["stars"],
      description: json["description"],
      location: json["location"],
    );
    print('Données du model $DataModel');
  }
}

经过大量的打印,知道哪里是问题,它表明,所有的数据disapear上的数据服务,只是当我做list.map((e) => DataModel.fromJson(e)).toList();我做的一切一样,在教程中,但它不工作。
谢谢你帮忙

6rqinv9w

6rqinv9w1#

DataModel类包含price字段,为int,但API给你的格式为String,所以要么解析为int,要么将类型改为String

String price;

--或--

将Json方法更改为

factory DataModel.fromJson(Map<String, dynamic> json) {
    return DataModel(
      name: json["name"],
      img: json["img"],
      price: num.parse(json["price"]).toDouble(), // here it is changed
      people: json["people"],
      stars: json["stars"],
      description: json["description"],
      location: json["location"],
    );
  }

复制粘贴即可。
同时将pricetype更改为dobule,因为它将转换为double

double price

相关问题