模型类中的列表不存储在Controller类的新列表中

发布于 2025-01-29 00:13:54 字数 4074 浏览 3 评论 0原文

**Product Modelclass which extracted from json file**


class Product {
  int? _totalSize;
  int? _typeId;
  int? _offset;
  late List<ProductModel> _products;
   List<ProductModel> get products=> _products;

  Product({required totalSize, required typeId, required offset, required products}){
    this. _totalSize=totalSize;
    this. _typeId=typeId;
    this. _offset=offset;
    this. _products=products;
  }

  Product.fromJson(Map<String, dynamic> json) {
    _totalSize = json['total_size'];
    _typeId = json['type_id'];
    _offset = json['offset'];
    if (json['productModel'] != null) {
      _products= <ProductModel>[];
      json['products'].forEach((v) {
        _products.add(new ProductModel.fromJson(v));
      });
    }
  }

}

class ProductModel {
  int? id;
  String? name;
  String? description;
  int? price;
  int? stars;
  String? img;
  String? location;
  String? createdAt;
  String? updatedAt;
  int? typeId;

  ProductModel(
      {this.id,
        this.name,
        this.description,
        this.price,
        this.stars,
        this.img,
        this.location,
        this.createdAt,
        this.updatedAt,
        this.typeId});

  ProductModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    description = json['description'];
    price = json['price'];
    stars = json['stars'];
    img = json['img'];
    location = json['location'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
    typeId = json['type_id'];
  }


}

这是我的api_client类,扩展了GETX从服务器

 import 'package:get/get.dart';

   class Api_client extends GetConnect{
    late String token;
    late String AppbaseUrl;
    late Map<String,String> _mainHeader;
     Api_client({required this.AppbaseUrl}){

       baseUrl=AppbaseUrl;
       timeout=Duration(seconds: 30);
       token="";
       _mainHeader={
         'Content-type':' application/json; charset-UTF-8',
         'Authorization':' Bearer $token',
       };
     }

    Future <Response> getData(String uri) async{

       try{
             Response response = await get(uri);
             return response;
       }catch(e){
             return Response(statusCode: 1,statusText: e.toString());
       }


     }


  }

**This is Popular_Product_List_Repo class extending Getx 
   getservices to get response from Api_client** 

    import 'package:get/get.dart';
import 'package:untitled/data/api/Api_client.dart';

class Popular_Product_List_Repo extends GetxService{

 final Api_client apiClient;

 Popular_Product_List_Repo({ required this.apiClient});

 Future <Response> get_popular_product_list()async{

  return await 
  apiClient.getData("/api/v1/products/popular");

 }



}

这是我的控制器类Prounder_product_controller,负责从Pusone_product_list_repo中获得响应新创建的列表,list_popular_product_list = [];要在我的ui 上显示列表的

 import 'package:get/get.dart';
import 'package:untitled/data/Repository/Popular_Product_List_Repo.dart';
import 'package:untitled/data/models/Products_model.dart';

class Popular_Product_Controller extends GetxController{
final   Popular_Product_List_Repo popular_product_repo ;

List<dynamic>_Popular_product_list=[];

Popular_Product_Controller({required this.popular_product_repo});

Future getPopular_Product_list() async{
  Response response=await popular_product_repo.get_popular_product_list();
  if(response.statusCode==200){
     print("got products");
     _Popular_product_list=[];
     _Popular_product_list.addAll(Product.fromJson(response.body).products);
     print(_Popular_product_list);
    update();
  }else{

  }


}




}

问题是,我想确保服务器的响应正确并且存储在我的列表中_popular_product_list中没有任何问题,我在pucun_product_controller中创建的响应我写了打印语句哪个是有产品的,_popular_product_list本身可以检查数据是否在_popular_product_list内部,无论何时我运行它都不显示任何语句,这意味着getPopular_product_list()均没有正常工作,所以我期望的是什么,所以列出了什么是错误的,列表产品是什么,列表产品是什么不存储_popular_product_list?

**Product Modelclass which extracted from json file**


class Product {
  int? _totalSize;
  int? _typeId;
  int? _offset;
  late List<ProductModel> _products;
   List<ProductModel> get products=> _products;

  Product({required totalSize, required typeId, required offset, required products}){
    this. _totalSize=totalSize;
    this. _typeId=typeId;
    this. _offset=offset;
    this. _products=products;
  }

  Product.fromJson(Map<String, dynamic> json) {
    _totalSize = json['total_size'];
    _typeId = json['type_id'];
    _offset = json['offset'];
    if (json['productModel'] != null) {
      _products= <ProductModel>[];
      json['products'].forEach((v) {
        _products.add(new ProductModel.fromJson(v));
      });
    }
  }

}

class ProductModel {
  int? id;
  String? name;
  String? description;
  int? price;
  int? stars;
  String? img;
  String? location;
  String? createdAt;
  String? updatedAt;
  int? typeId;

  ProductModel(
      {this.id,
        this.name,
        this.description,
        this.price,
        this.stars,
        this.img,
        this.location,
        this.createdAt,
        this.updatedAt,
        this.typeId});

  ProductModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    description = json['description'];
    price = json['price'];
    stars = json['stars'];
    img = json['img'];
    location = json['location'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
    typeId = json['type_id'];
  }


}

This is my Api_client class extending Getx to get response from server

 import 'package:get/get.dart';

   class Api_client extends GetConnect{
    late String token;
    late String AppbaseUrl;
    late Map<String,String> _mainHeader;
     Api_client({required this.AppbaseUrl}){

       baseUrl=AppbaseUrl;
       timeout=Duration(seconds: 30);
       token="";
       _mainHeader={
         'Content-type':' application/json; charset-UTF-8',
         'Authorization':' Bearer $token',
       };
     }

    Future <Response> getData(String uri) async{

       try{
             Response response = await get(uri);
             return response;
       }catch(e){
             return Response(statusCode: 1,statusText: e.toString());
       }


     }


  }

**This is Popular_Product_List_Repo class extending Getx 
   getservices to get response from Api_client** 

    import 'package:get/get.dart';
import 'package:untitled/data/api/Api_client.dart';

class Popular_Product_List_Repo extends GetxService{

 final Api_client apiClient;

 Popular_Product_List_Repo({ required this.apiClient});

 Future <Response> get_popular_product_list()async{

  return await 
  apiClient.getData("/api/v1/products/popular");

 }



}

This is my controller class Popular_Product_Controller which is responsible for to get response from Popular_Product_List_Repo and retrieve the list and store the list in my new created List which is List_Popular_product_list=[]; to show the list on my UI

 import 'package:get/get.dart';
import 'package:untitled/data/Repository/Popular_Product_List_Repo.dart';
import 'package:untitled/data/models/Products_model.dart';

class Popular_Product_Controller extends GetxController{
final   Popular_Product_List_Repo popular_product_repo ;

List<dynamic>_Popular_product_list=[];

Popular_Product_Controller({required this.popular_product_repo});

Future getPopular_Product_list() async{
  Response response=await popular_product_repo.get_popular_product_list();
  if(response.statusCode==200){
     print("got products");
     _Popular_product_list=[];
     _Popular_product_list.addAll(Product.fromJson(response.body).products);
     print(_Popular_product_list);
    update();
  }else{

  }


}




}

Problem is I want to make sure that response from server is right and stored without any issue in my list _Popular_product_list which I created in the Popular_Product_Controller I wrote print statement which is got products and _Popular_product_list itself to check that data is inside the _Popular_product_list or not so whenever I run its not showing either any statements which means the function getPopular_Product_list() is not working as I expected so what is went wrong and why list products is not storing inside the _Popular_product_list ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怼怹恏 2025-02-05 00:13:54
In order to verify if you are getting some data.. you can use the **Either** class in Dart which can imported from pub.dev. its make it easy to handle

for example, 

final Either<String, List<Product>> result =
        await getProductList();
  
    result.fold((exception) {
      CustomToast.showErrorToast(Messages.UNABLE_TO_LOAD_PRODUCT_LIST);
    }, (products) async {
      //get products here and you can do what you want
      }
In order to verify if you are getting some data.. you can use the **Either** class in Dart which can imported from pub.dev. its make it easy to handle

for example, 

final Either<String, List<Product>> result =
        await getProductList();
  
    result.fold((exception) {
      CustomToast.showErrorToast(Messages.UNABLE_TO_LOAD_PRODUCT_LIST);
    }, (products) async {
      //get products here and you can do what you want
      }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文