Home > Software engineering >  i want to convert json to a compatible dart format help me i'm beginner in flutter
i want to convert json to a compatible dart format help me i'm beginner in flutter

Time:06-28

i'm learning flutter & dart and i was trying to implement state management and REST API data in the exercice but i got the same error since 2 days. My process is the same with the tutorail tutorial link but i got a mistake somewhere there is my Data service

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>[];
    }
  }
}

and the Data Model

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

after a lot of print to know where is the problem it shown that all of the data disapear on the data Service just when i do list.map((e) => DataModel.fromJson(e)).toList(); i do everything like in the tutorial but it don't work.

thank for your help

CodePudding user response:

DataModel class contains price field which is int but api gives you in the form of String so either you parse it into int or Change the type to String

String price;

--------OR--------

change fromJson method to

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"],
    );
  }

just copy and paste it it will work

  • Related