【问题标题】:How to show network data in Gridview如何在 Gridview 中显示网络数据
【发布时间】:2020-09-04 01:37:26
【问题描述】:

我有一个GridView,我能够显示静态列表中的数据。现在,我想显示来自 api 的数据,我知道可以使用 FutureBuilder 来完成,但我不知道该怎么做。

这是我的 api 调用:

  Future<Map> getJson() async {

  String apiUrl = 'http://3.127.255.230/rest_ci/api/products/show_all_prod?rest_id=6';

Map<String,String> headers = {
  http.Response response = await http
   .get(apiUrl);


  return json.decode(response.body); // returns a List type
}


void dataShower() async{
  getJson();
    Map _data = await getJson();
    print(_data);
}

这是我的GridView 以及当地的食物清单:

     GridView.builder(
              shrinkWrap: true,
              primary: false,
              physics: NeverScrollableScrollPhysics(),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                childAspectRatio: MediaQuery.of(context).size.width /
                    (MediaQuery.of(context).size.height / 1.25),
              ),
              itemCount: foods == null ? 0 :foods.length,
              itemBuilder: (BuildContext context, int index) {
//                Food food = Food.fromJson(foods[index]);
                Map food = foods[index];
//                print(foods);
//                print(foods.length);
                return GridProduct(
                  img: food['img'],
                  isFav: false,
                  name: food['name'],
                  rating: 5.0,
                  raters: 23,
                );
              },
            ),

这是我的 api 响应:

{
    "status": "SUCCESS",
    "data": [
        {
            "id": "1",
            "name": "Fruit Salad",
            "slug": "fruit-salad",
            "description": "Nulla quis lorem ut libero malesuada feugiat. Lorem ips sit amet, consectetur adipiscing elit. Curabitur aliquet quamid dui posuereblandit. Pellentesque in ipsum id orci porta dapibus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec velit neque, auctor sit amet aliquam vel, ullamcorper sit amet ligula. Donec rutrum congue leo eget malesuada. Vivamus magna justo,",
            "unit_price": "50",
            "sale_unit_price": "0",
            "rest_id": "1",
            "cat_id": "4",
            "icon": "http://3.127.255.230/rest_ci/assets/uploads/products/1589784733__food12.jpg",
            "added_date": "2020-05-18 06:52:13",
            "updated_date": "2020-05-18 06:52:13",
            "status": "1"
        },
        {
            "id": "2",
            "name": "Steak",
            "slug": "steak",
            "description": "this is just dummy description for all the products.\r\nthis is just dummy 
                        for all the products.\r\nthis is just dummy description for all the products.",
            "unit_price": "34",
            "sale_unit_price": "0",
            "rest_id": "1",
            "cat_id": "3",
            "icon": "http://3.127.255.230/rest_ci/assets/uploads/products/1589784928__food12.jpg",
            "added_date": "2020-05-18 06:55:28",
            "updated_date": "2020-05-18 06:55:28",
            "status": "1"
        }
    ]
}

我想将该 api 调用的结果添加到 GridView(只是名称和图标),现在它已填充在静态列表中,任何帮助将不胜感激。

【问题讨论】:

    标签: api flutter dart gridview


    【解决方案1】:

    使用 FutureBuilder (https://flutter.dev/docs/cookbook/networking/fetch-data) 显示来自未来方法的数据,如 getJson()

    并在getJson()中,将json数据转换为dart类模型

    【讨论】:

    • 我已经在 listview.builder 中使用了 future builder,但我不知道如何使用 gridview 来实现
    【解决方案2】:

    先将json数据转成dart Model

    class List {
      String status;
      List<Data> data;
    
      List({this.status, this.data});
    
      List.fromJson(Map<String, dynamic> json) {
        status = json['status'];
        if (json['data'] != null) {
          data = new List<Data>();
          json['data'].forEach((v) {
            data.add(new Data.fromJson(v));
          });
        }
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['status'] = this.status;
        if (this.data != null) {
          data['data'] = this.data.map((v) => v.toJson()).toList();
        }
        return data;
      }
    }
    
    class Data {
      String id;
      String name;
      String slug;
      String description;
      String unitPrice;
      String saleUnitPrice;
      String restId;
      String catId;
      String icon;
      String addedDate;
      String updatedDate;
      String status;
    
      Data(
          {this.id,
          this.name,
          this.slug,
          this.description,
          this.unitPrice,
          this.saleUnitPrice,
          this.restId,
          this.catId,
          this.icon,
          this.addedDate,
          this.updatedDate,
          this.status});
    
      Data.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        name = json['name'];
        slug = json['slug'];
        description = json['description'];
        unitPrice = json['unit_price'];
        saleUnitPrice = json['sale_unit_price'];
        restId = json['rest_id'];
        catId = json['cat_id'];
        icon = json['icon'];
        addedDate = json['added_date'];
        updatedDate = json['updated_date'];
        status = json['status'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['id'] = this.id;
        data['name'] = this.name;
        data['slug'] = this.slug;
        data['description'] = this.description;
        data['unit_price'] = this.unitPrice;
        data['sale_unit_price'] = this.saleUnitPrice;
        data['rest_id'] = this.restId;
        data['cat_id'] = this.catId;
        data['icon'] = this.icon;
        data['added_date'] = this.addedDate;
        data['updated_date'] = this.updatedDate;
        data['status'] = this.status;
        return data;
      }
    }
    

    并将Future&lt;Map&gt; getJson() async 更改为List getJson() async 在getJsone中返回List.fromJson(json.decode(response.body))

    那么你可以像使用静态列表一样使用这个列表

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多