I have static Gridview from local List How to make it dynamic

早过忘川 提交于 2021-01-29 06:05:29

问题


i have gridview from local list now i want to populate that gridview from api any idea how to do it,

this is how my api response look like

{
    "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"
  },

    ]
}

this is my static (local list) code for 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,
                );
              },
            ),

this is my GridProduct class

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,
            ),
          ),




        ],
      ),

    );
  }
}

and this my api request i am printing response but i do not know how to populate that gridview from Api response.

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

回答1:


You can use FutureBuilder widget

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


来源:https://stackoverflow.com/questions/61873762/i-have-static-gridview-from-local-list-how-to-make-it-dynamic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!