简体   繁体   中英

How to get data from json file to GridView.builder in flutter?

I want to fetch data from the JSON file to GridView.builder(), I watched a lot of videos but I didn't achieve any results, please help me to do that. This is the JSON file I want to use: My JSON file here

{
    "Ads": {
        "show_ads": true,
        "InterAd": "unity",
        "bannerAd": "unity",
    },

    "LOCAL_BANNER": {
        "show": true,
        "image": "image1.jpg",
        "url": "https://www.google.com"
    },
    
    "MORE_APPS": [{
            "title": "Get app now",
            "img": "www.google.com",
            "url": "www.google.com",
            "country": "IN"
        }, {
            "title": "Get app now",
            "img": "www.google.com",
            "url": "www.google.com",
            "country": ""
        }
    ],

}

I WANT TO fill data to grid view using MORE_APPS key. Thank you;

1st.. store your json in an asset folder.. preferribly in rootfolder/assets

2.. register your asset in your pubspec.yaml file

3.. create your model.. preferribly using https://app.quicktype.io/dart/. . copy your json data there, and it will generate your model for you.

    // To parse this JSON data, do
//
//     final myData = myDataFromJson(jsonString);

import 'dart:convert';

MyData myDataFromJson(String str) => MyData.fromJson(json.decode(str));

String myDataToJson(MyData data) => json.encode(data.toJson());

class MyData {
  MyData({
    this.ads,
    this.localBanner,
    this.moreApps,
  });

  Ads? ads;
  LocalBanner? localBanner;
  List<MoreApp>? moreApps;

  factory MyData.fromJson(Map<String, dynamic> json) => MyData(
    ads: Ads.fromJson(json["Ads"]),
    localBanner: LocalBanner.fromJson(json["LOCAL_BANNER"]),
    moreApps: List<MoreApp>.from(json["MORE_APPS"].map((x) => MoreApp.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "Ads": ads!.toJson(),
    "LOCAL_BANNER": localBanner!.toJson(),
    "MORE_APPS": List<dynamic>.from(moreApps!.map((x) => x.toJson())),
  };
}

class Ads {
  Ads({
    this.showAds,
    this.interAd,
    this.bannerAd,
  });

  bool? showAds;
  String? interAd;
  String? bannerAd;

  factory Ads.fromJson(Map<String, dynamic> json) => Ads(
    showAds: json["show_ads"],
    interAd: json["InterAd"],
    bannerAd: json["bannerAd"],
  );

  Map<String, dynamic> toJson() => {
    "show_ads": showAds,
    "InterAd": interAd,
    "bannerAd": bannerAd,
  };
}

class LocalBanner {
  LocalBanner({
    this.show,
    this.image,
    this.url,
  });

  bool? show;
  String? image;
  String? url;

  factory LocalBanner.fromJson(Map<String, dynamic> json) => LocalBanner(
    show: json["show"],
    image: json["image"],
    url: json["url"],
  );

  Map<String, dynamic> toJson() => {
    "show": show,
    "image": image,
    "url": url,
  };
}

class MoreApp {
  MoreApp({
    this.title,
    this.img,
    this.url,
    this.country,
  });

  String? title;
  String? img;
  String? url;
  String? country;

  factory MoreApp.fromJson(Map<String, dynamic> json) => MoreApp(
    title: json["title"],
    img: json["img"],
    url: json["url"],
    country: json["country"],
  );

  Map<String, dynamic> toJson() => {
    "title": title,
    "img": img,
    "url": url,
    "country": country,
  };
}

4.. create your function that converts the json data to the model..

import 'package:flutter/services.dart';

Future<MyData> readJsonFile() async {
  final String response = await rootBundle.loadString('assets/filejson.json');
  final data = myDataFromJson(response);
  return data;
}

5.. declare a global variable.. in this case i have named the model MyData.. so declare that globally

MyData data = MyData();
  1. in your initstate make sure to assign your value to the variable data

     void initState() { readJsonFile().then((value) => setState((){ data = value; })); super.initState();}

then do the following

FutureBuilder(
        future: readJsonFile(),
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        if(snapshot.hasData){
          return Center(
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      Container(
                        color: Colors.lightGreen,
                        child: Column(
                          children: [
                            Text(
                                "Ads"
                            ),
                            Text("show_ads: ${data.ads!.showAds}"),
                            Text("InterAd : ${data.ads!.interAd}"),
                            Text("bannerAd: ${data.ads!.bannerAd}")
                          ],
                        ),
                      ),
                      Container(
                        color: Colors.amber,
                        child: Column(
                          children: [
                            Text(
                                "LOCAL_BANNER"
                            ),
                            Text("show: ${data.localBanner!.show}"),
                            Text("image: ${data.localBanner!.image}"),
                            Text("url: ${data.localBanner!.url}"),
                          ],
                        ),
                      )
                    ],
                  ),
                  SizedBox(height: 40,),
                  Expanded(
                    child: GridView.builder(
                        itemCount: data.moreApps!.length,
                        gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
                            maxCrossAxisExtent: 200,
                            childAspectRatio: 3 / 2,
                            crossAxisSpacing: 20,
                            mainAxisSpacing: 20),
                        itemBuilder: (context, index) {
                          return Container(
                            child: Column(
                              children: [
                                Text(data.moreApps![index].title!),
                                Text(data.moreApps![index].img!),
                                Text(data.moreApps![index].url!),
                                Text(data.moreApps![index].country!),
                              ],
                            ),
                          );
                        }),
                  ),
                ],
              )
          );        }
        else{
          return const CircularProgressIndicator();
        }
      },)

这是结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM