Home > Software design >  Stuck with json in flutter
Stuck with json in flutter

Time:02-17

I dont know the problem is because when debuging there isn't error info but the value of json is empty when I print info.lenght

class _HomePageState extends State<HomePage> {
  
  List info = [];
  _initData(){
    DefaultAssetBundle.of(context).loadString("json/info.json").then((value){
      info = jsonDecode(value);
    });
  }

  @override
  void iniState(){
    super.initState();
    _initData();
  }

and below is my json code in json/info.json

[
    {
        "title": "Glue",
        "img": "assets/ex1.png"
    },
    {
        "title": "Abs",
        "img": "assets/ex2.png"
    },
    {
        "title": "Legs",
        "img": "assets/ex3.png"
    },
    {
        "title": "Arms",
        "img": "assets/ex4.png"
    }
]

and how to we print the img and title value of json in dart?

CodePudding user response:

You have to first create a model class for your json response.

// To parse this JSON data, do
//
//     final jsonModel = jsonModelFromJson(jsonString);

import 'dart:convert';

List<JsonModel> jsonModelFromJson(String str) => List<JsonModel>.from(json.decode(str).map((x) => JsonModel.fromJson(x)));

String jsonModelToJson(List<JsonModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class JsonModel {
    JsonModel({
        this.title,
        this.img,
    });

    String title;
    String img;

    factory JsonModel.fromJson(Map<String, dynamic> json) => JsonModel(
        title: json["title"] == null ? null : json["title"],
        img: json["img"] == null ? null : json["img"],
    );

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

then just use this model class to decode your json file.

var result = JsonModel.fromJson(jsonResponse);

Later, you can just use result.title or result.img to get the data

CodePudding user response:

You have to add your json file into pubspec.yaml file.

 flutter:
   assets:
     - json/info.json

Before loading page view, you should load values from your json file and assign a list in initState. After that, you can use list as map by [index][header].

class JsonResult extends StatefulWidget {
   const JsonResult({Key? key}) : super(key: key);

   @override
   _JsonResultState createState() => _JsonResultState();
}

class _JsonResultState extends State<JsonResult> {
  var jsonList = [];
  @override
  void initState() {
    rootBundle.loadString("json/info.json").then((value) {
      jsonList = json.decode(value);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ListView.builder(
          itemBuilder: (context, index) {
            return ListTile(
              leading: Image.asset(jsonList[index]["img"]),
              title: Text(jsonList[index]["title"]),
            );
          },
          itemCount: jsonList.length,
        ),
      ),
    );
  }
}
  • Related