简体   繁体   English

我正在尝试从 API 获取数据但出现错误

[英]I am trying to get data from API but having error

This is my model class and I am trying to get all the data but getting error and don't know why.这是我的 model class,我正在尝试获取所有数据,但出现错误,不知道为什么。

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'

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,问题是您尝试解析数据的方式,您不需要遍历每个元素来解析它,在您的 model 中,只需让它返回这样的列表类型,

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,在您看来 model 您可以像这样解析从 response.body 中提取的数据,

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

} }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试在 flutter 上发出获取请求时出错 - I am having an error while trying to make a get request on flutter 我正在尝试从 newsapi.org 获取数据但遇到问题 - I am trying to fetch data from newsapi.org but having issue 我正在尝试使用 getx 获取 slider 图像但出现错误 - i am trying to fetch slider image using getx but having error 我在尝试使用 RSS 访问数据时遇到问题 - i am having issue while trying to access data using rss 我无法从 Google Place API 自动完成获取数据 - I am having trouble getting data from Google Place API AutoComplete 我在尝试将数据从云 Firestore 带到我的 flutter 应用程序时遇到此错误 - I am getting this error while am trying to bring data from cloud firestore to my flutter app 我正在尝试使用从API获得的数据创建列表视图 - I am trying to create a list view with the data that I got from API 我在尝试将字符串数据分配给 Integer 变量时遇到问题 - I am having problem when i am trying to assign String data to Integer variable 我正在尝试从 API 中获取 TimeZones,但由于某种原因,它没有返回所有 timeZones - I am trying to get TimeZones from an API in flutter but due to some reason its not returning all timeZones 我正在尝试从 api 获取数据并将其显示在 DropDownButton 中。 问题是快照返回 null - I am trying to fetch data from the api and display it in a DropDownButton. problem is that snapshot is returning null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM