flutterflutter-http

Problem receiving information / Exception has occurred TypeError


I want to read my information from the API. But facing this error. enter image description here

This is the code I wrote:

import '../models/LocationListApi.dart';
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;

class Network {
  static Uri url = Uri.parse(
      "http://pelak.puladin.com/laravel-api/api/v1/places?category_id=11");

  static List<PlacesEntity> location = [];

  static void getData() async {
    location.clear();
    var response = await http.get(url);
    var jsonDecode = convert.jsonDecode(response.body);

    var finalResponse = PlacesEntity.fromJson(jsonDecode['data']);

    for (var json in jsonDecode) {
      location.add(PlacesEntity.fromJson(json));
    }

    print(jsonDecode);
  }
}

The model I made to display information based on Jsonis as follows: My model:

// ignore_for_file: file_names

class PlacesEntity {
  List<Place> places;

  PlacesEntity({
    required this.places,
  });

  factory PlacesEntity.fromJson(Map<String, dynamic> json) {
    return PlacesEntity(
      places: List<Place>.from(json['places'].map((x) => Place.fromJson(x))),
    );
  }
}

class Place {
  int id;
  int pelak;
  String name;
  String intro;
  String description;
  String latitude;
  String longitude;
  String address;
  String phone;
  String email;
  String website;
  String instagram;
  String image;
  String category;
  String ads;
  String adsLink;

  Place({
    required this.id,
    required this.pelak,
    required this.name,
    required this.intro,
    required this.description,
    required this.latitude,
    required this.longitude,
    required this.address,
    required this.phone,
    required this.email,
    required this.website,
    required this.instagram,
    required this.image,
    required this.category,
    required this.ads,
    required this.adsLink,
  });

  factory Place.fromJson(Map<String, dynamic> json) {
    return Place(
      id: json['id'],
      pelak: json['pelak'],
      name: json['name'],
      intro: json['intro'],
      description: json['description'],
      latitude: json['latitude'],
      longitude: json['longitude'],
      address: json['address'],
      phone: json['phone'],
      email: json['email'],
      website: json['website'],
      instagram: json['instagram'],
      image: json['image'],
      category: json['category'],
      ads: json['ads'],
      adsLink: json['ads_link'],
    );
  }
}

class MyJson {
  PlacesEntity data;
  int status;

  MyJson({
    required this.data,
    required this.status,
  });

  factory MyJson.fromJson(Map<String, dynamic> json) {
    return MyJson(
      data: PlacesEntity.fromJson(json['data']),
      status: json['status'],
    );
  }
}

I tried to make it into a list that I could read in the app, but I couldn't. The problem may be with my model. Anyway, this is a problem that has arisen for me. I would be grateful if you could help me


Solution

  • class ApiClass{
      Future<List<Place>> fetchUsers()async{
    
        final response = await http.get(Uri.parse("http://pelak.puladin.com/laravel-api/api/v1/places?category_id=11"));
    
        List listData = jsonDecode(response.body)["data"]["places"];
    
        if(response.statusCode == 200){
          var result = listData.map((e) => Place.fromJson(e)).toList();
          for(int i = 0; i<result.length; i++){
            print(result[i].name);
          }
          return result;
        }else{
          throw Exception("Error");
        }
      }
    }
    

    Now, to access this. Create an instance of Network class and a late initialized List where you want to use it.

    final Network networkObject = Network();
    late List<Place> placeList;
    

    Create a new async method and call it in initState:

    void apiCall()async{
        placeList = await networkObject.getData();
    }