0

This is my model class and I am trying to get all the data but getting error and don't know why.

HomePageModel homePageModelFromJson(String str) => HomePageModel.fromJson(json.decode(str));

String homePageModelToJson(HomePageModel data) => json.encode(data.toJson());

class HomePageModel with ChangeNotifier {
  HomePageModel({
    this.data,
  });

  List<Datum>? data;

  factory HomePageModel.fromJson(Map<String, dynamic> json) => HomePageModel(
    data: List<Datum>.from(json["data"]!.map((x) => Datum.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "data": List<dynamic>.from(data!.map((x) => x.toJson())),
  };
}

class Datum {
  Datum({
    this.schoolid,
    this.name,
    this.logo,
    this.address,
    this.contact,
    this.principalname,
    this.principalcontact,
    this.slogan,
    this.webAddress,
    this.description,
    this.email,
    this.pan,
    this.establishedYear,
  });

  String? schoolid;
  String? name;
  String? logo;
  String? address;
  String? contact;
  String? principalname;
  String? principalcontact;
  String? slogan;
  String? webAddress;
  String? description;
  String? email;
  String? pan;
  int? establishedYear;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
    schoolid: json["schoolid"],
    name: json["name"],
    logo: json["logo"],
    address: json["address"],
    contact: json["contact"],
    principalname: json["principalname"],
    principalcontact: json["principalcontact"],
    slogan: json["slogan"],
    webAddress: json["web_address"] == null ? null : json["web_address"],
    description: json["description"] == null ? null : json["description"],
    email: json["email"],
    pan: json["pan"],
    establishedYear: json["established_year"],
  );

  Map<String, dynamic> toJson() => {
    "schoolid": schoolid,
    "name": name,
    "logo": logo,
    "address": address,
    "contact": contact,
    "principalname": principalname,
    "principalcontact": principalcontact,
    "slogan": slogan,
    "web_address": webAddress == null ? null : webAddress,
    "description": description == null ? null : description,
    "email": email,
    "pan": pan,
    "established_year": establishedYear,
  };
}

This is how I am trying to fetch data:

class HomePageModels with ChangeNotifier{
  List<HomePageModel> _hItem = [];

  List<HomePageModel> get hItem{
    return [..._hItem];
  }

  Future<void> getHomeData(BuildContext context) async{
    const url = "https://shikshyasoftware.com.np/CoreApplicationandAPIService-4617993073/api/school";
    try{
      // EasyLoading.show(status: 'Loading...');
      final response = await http.get(Uri.parse(url));
      final extractedData = json.decode(response.body);
      List<HomePageModel> loadedHomeData = [];
      if(extractedData == null){
        return;
      }
      if(response.statusCode == 200){
        print(extractedData);
      }
      extractedData.forEach((element){
        loadedHomeData.add(HomePageModel.fromJson(element));
      });
      _hItem = loadedHomeData;
      // EasyLoading.showSuccess("data fetched sucessfull");
      notifyListeners();
    }catch(e){
      rethrow;
    }
  }
}

But I am getting error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f'
Biffen
  • 6,249
  • 6
  • 28
  • 36
Saurav
  • 132
  • 1
  • 12
  • If you get data from API refer my answer [here](https://stackoverflow.com/a/68709502/13997210) or [here](https://stackoverflow.com/a/68533647/13997210) or [here](https://stackoverflow.com/a/68594656/13997210) hope it's helpful to you – Ravindra S. Patil Jan 17 '22 at 08:51

2 Answers2

0

The problem is the way you are trying to parse the data, you don't need to loop over every element to parse it, in your model just make it return a list type like this,

class HomePageModel with ChangeNotifier {
  List<Datum>? data;

  HomePageModel({this.data});

  HomePageModel.fromJson(Map<String, dynamic> json) {
    if (json['data'] != null) {
      data = <Datum>[];
      json['data'].forEach((v) {
        data!.add(new Datum.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.data != null) {
      data['data'] = this.data!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Datum {
  Datum({
    this.schoolid,
    this.name,
    this.logo,
    this.address,
    this.contact,
    this.principalname,
    this.principalcontact,
    this.slogan,
    this.webAddress,
    this.description,
    this.email,
    this.pan,
    this.establishedYear,
  });

  String? schoolid;
  String? name;
  String? logo;
  String? address;
  String? contact;
  String? principalname;
  String? principalcontact;
  String? slogan;
  String? webAddress;
  String? description;
  String? email;
  String? pan;
  int? establishedYear;

  Datum.fromJson(Map<String, dynamic> json) {
    schoolid = json["schoolid"];
    name = json["name"];
    logo = json["logo"];
    address = json["address"];
    contact = json["contact"];
    principalname = json["principalname"];
    principalcontact = json["principalcontact"];
    slogan = json["slogan"];
    webAddress = json["web_address"];
    description = json["description"];
    email = json["email"];
    pan = json["pan"];
    establishedYear = json["established_year"];
  }
  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['schoolid'] = this.schoolid;
    data['name'] = this.name;
    data['logo'] = this.logo;
    data['address'] = this.address;
    data['contact'] = this.contact;
    data['principalname'] = this.principalname;
    data['principalcontact'] = this.principalcontact;
    data['slogan'] = this.slogan;
    data['web_address'] = this.webAddress;
    data['description'] = this.description;
    data['email'] = this.email;
    data['pan'] = this.pan;
    data['established_year'] = this.establishedYear;
    return data;
  }
}

and in your view model you can just parse the extracted data from response.body like this,

class HomePageModels with ChangeNotifier {
  HomePageModel? _hItem;

  HomePageModel get hItem {
    return _hItem!;
  }

  Future<void> getHomeData(BuildContext context) async {
    const url =
        "https://shikshyasoftware.com.np/CoreApplicationandAPIService- 
4617993073/api/school";
    try {
      // EasyLoading.show(status: 'Loading...');
      final response = await http.get(Uri.parse(url));
      final extractedData = json.decode(response.body);
      if (extractedData == null) {
        return;
      }
      if (response.statusCode == 200) {
        print(extractedData);
      }
      HomePageModel loadedHomeData = 
HomePageModel.fromJson(extractedData);
      _hItem = loadedHomeData;
      // EasyLoading.showSuccess("data fetched sucessfull");
      notifyListeners();
    } catch (e) {
      rethrow;
    }
  }
}
VaasFPS
  • 43
  • 3
  • i am not able to asign _hItem = loadedHomeData; this – Saurav Jan 17 '22 at 08:48
  • Have you changed _hItem from list type to object ? like this HomePageModel? _hItem; HomePageModel get hItem { return _hItem!; } – VaasFPS Jan 17 '22 at 08:53
  • yes i did and it removed the error but i am getHomeData inside didChangedependency and using Listview.builder but i am still getting error – Saurav Jan 17 '22 at 09:36
  • it is saying Null check operator used on a null value and also Error: Could not find the correct Provider above this HomePageDesign Widget – Saurav Jan 17 '22 at 09:38
  • copy and paste whole code that i provided and replace it your file. – VaasFPS Jan 17 '22 at 11:06
-1
 getHomeData(BuildContext context) async {
const url =
    "https://shikshyasoftware.com.np/CoreApplicationandAPIService-4617993073/api/school";
try {
  // EasyLoading.show(status: 'Loading...');
  final response = await http.get(Uri.parse(url));

  if (response.statusCode == 200) {
    final extractedData = json.decode(response.body);
    List loadedHomeData = extractedData;
    _hItem = loadedHomeData.map((e) => HomePageModel.fromJson(e)).toList();
  }
  notifyListeners();
  return _hItem;
} catch (e) {
  rethrow;
}

}