【问题标题】:I have static Gridview from local List How to make it dynamic我有来自本地列表的静态 Gridview 如何使其动态化
【发布时间】:2020-09-04 11:56:34
【问题描述】:

我有来自本地列表的 gridview 现在我想从 api 填充那个 gridview 任何想法如何做到这一点,

这就是我的 api 响应的样子

{
    "status": "SUCCESS",
    "data": [
         {
    "img": "http://3.127.255.230/rest_ci/assets/uploads/products/1589784928__food12.jpg",
    "name": "Fruit Salad"
  },
  {
    "img": "http://3.127.255.230/rest_ci/assets/uploads/products/1589784733__food12.jpg",
    "name": "Fruit Salad"
  },
  {
    "img": "assets/food3.jpeg",
    "name": "Hamburger"
  },

    ]
}

这是我的 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,
                );
              },
            ),

这是我的 GridProduct 类

import 'package:flutter/material.dart';
import 'package:restaurant_ui_kit/screens/details.dart';
import 'package:restaurant_ui_kit/util/const.dart';
import 'package:restaurant_ui_kit/widgets/smooth_star_rating.dart';

class GridProduct extends StatelessWidget {

  final String name;
  final String img;



  GridProduct({
    Key key,
    @required this.name,
    @required this.img,
    })
      :super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: ListView(
        shrinkWrap: true,
        primary: false,
        children: <Widget>[
          Stack(
            children: <Widget>[
              Container(
                height: MediaQuery.of(context).size.height / 3.6,
                width: MediaQuery.of(context).size.width / 2.2,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(8.0),
                  child: Image.asset(
                    "$img",
                    fit: BoxFit.cover,
                  ),
                ),
              ),



          Padding(
            padding: EdgeInsets.only(bottom: 2.0, top: 8.0),
            child: Text(
              "$name",
              style: TextStyle(
                fontSize: 20.0,
                fontWeight: FontWeight.w900,
              ),
              maxLines: 2,
            ),
          ),




        ],
      ),

    );
  }
}

这是我的 api 请求,我正在打印响应,但我不知道如何从 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);
}

【问题讨论】:

    标签: api flutter dart gridview


    【解决方案1】:

    你可以使用FutureBuilder小部件

    FutureBuilder<Map>(
        future: getJson(), // your function which calls the API and return the response
        builder: (BuildContext context, AsyncSnapshot<Map> snapshot) {
          if (snapshot.hasData) {
            // sanpshot.data will contain the response got from API
            // snapshot.data['data'] should give you the list of foods which you can
            // use with GridView.builder
            List foods = snapshot.data['data'];
            return GridView.builder(
               itemCount: foods.length,
               itemBuilder: (BuildContext context, int index) {
                 Map food = foods[index];
                 return GridProduct(
                     img: food['img'],
                     isFav: false,
                     name: food['name'],
                     rating: 5.0,
                     raters: 23,
                 );
               }
            );
          }
          // handle if the API fails
        }
     );
    

    【讨论】:

    • 在你的答案第三行有这个错误....参数类型'GridView Function(BuildContext,AsyncSnapshot )'不能分配给参数类型'Widget Function(BuildContext, AsyncSnapshot>)'.
    • @shahid 感谢您指出错误...应该是AysncSnapshot&lt;Map&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    相关资源
    最近更新 更多