如何在Gridview中显示网络数据

时间:2020-05-18 09:28:59

标签: api flutter dart gridview

我有一个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(仅是名称和图标)中,因为它现在已填充在静态列表中,我们将不胜感激。

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

首先将json数据转换为dart模型

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<Map> getJson() async更改为List getJson() async 在getJsone中返回List.fromJson(json.decode(response.body))

然后您可以像静态列表一样使用此列表