Search code examples
jsonflutterandroid-listview

convert JSON to ListView.builder in flutter


I'm new in programming so please be patient with me, I'm trying to convert this JSON to be displayed like this design, I have done JSON decode but for sample JSON so I understand how it works but for complex one I'm confused so I really appreciate if any one help

JSON Code:

[
  {
    "Category": "Gro",
    "stores": [
      {
        "name": "market",
        "logo_url": "https://www.google.com/signpost-150x150.png",
        "phone_1": "1111111111",
        "phone_2": "1111111111",
        "location": "https://maps.google.com/location"
      },
      {
        "name": "mall",
        "logo_url": "https://www.google.com/signpost-150x150.png",
        "phone_1": "1111111111",
        "phone_2": "1111111111",
        "location": "https://maps.google.com/location"
      }
    ]
  },
  {
    "Category": "Food",
    "stores": [
      {
        "name": "Food Time",
        "logo_url": "https://www.google.com/signpost-150x150.png",
        "phone_1": "1111111111",
        "phone_2": "1111111111",
        "location": "https://maps.google.com/location"
      },
      {
        "name": "let's eat",
        "logo_url": "https://www.google.com/signpost-150x150.png",
        "phone_1": "1111111111",
        "phone_2": "1111111111",
        "location": "https://maps.google.com/location"
      }
    ]
  },
  {
    "Category": "Personal Care",
    "stores": [
      {
        "name": "Body",
        "logo_url": "https://www.google.com/signpost-150x150.png",
        "phone_1": "1111111111",
        "phone_2": "1111111111",
        "location": "https://maps.google.com/location"
      },
      {
        "name": "Hair",
        "logo_url": "https://www.google.com/signpost-150x150.png",
        "phone_1": "1111111111",
        "phone_2": "1111111111",
        "location": "https://maps.google.com/location"
      }
    ]
  }
]

#################################################

What I want to display

#################################################

This is what I have come up with

import 'package:side_menu.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:http/http.dart';
import 'dart:convert';

Future<List> shopsList() async {
  Response response = await get('JSON URL');
  if (response.statusCode == 200) {
    var shopsData = jsonDecode(response.body);
    return shopsData;
  } else {
    print(response.statusCode);
  }
}

class ShowShops extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: SideMenu(),
      appBar: AppBar(),
      body: Column(
        children: [
          Expanded(
            child: Container(
              child: FutureBuilder(
                  future: shopsList(),
                  builder: (context, shops) {
                    if (shops.hasData) {
                      return ListView.builder(
                        itemCount: shops.data.length,
                        itemBuilder: (BuildContext context, int index) {
                          Map shopInfo = shops.data[index];
                          String cat = shopInfo[index]['Category'];
                          return Card(
                            child: Text(cat),
                          );
                        },
                      );
                    }
                    return Center(
                      child: SpinKitWave(
                        color: Color(0xff023246),
                        size: 100,
                      ),
                      //CircularProgressIndicator(),
                    );
                  }),
            ),
          )
        ],
      ),
    );
  }
}

But I get error and I'm confused how to display shops under category

Thanks for help in advance


Solution

  • try my code

    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: Test(),
        );
      }
    }
    
    class Test extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(),
          body: FutureBuilder(
            future: http.get('https://dc-apps.net/map/services.json'),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return Center(child: CircularProgressIndicator());
              }
              List data = json.decode(snapshot.data.body);
              // print(data);
              List categoriesnames = [];
              List stores = [];
              data.forEach((element) {
                categoriesnames.add(element["Category"]);
                stores.add(element['stores']);
              });
    
              // return Text('see');
              return ListView.builder(
                itemCount: data.length,
                itemBuilder: (context, index) {
                  //      print(stores[index][index]['name']);
                  return CardItem(
                    categoryname: categoriesnames[index],
                    sotories: stores[index],
                  );
                },
              );
            },
          ),
        );
      }
    }
    
    class CardItem extends StatelessWidget {
      final String categoryname;
      List sotories;
      CardItem({this.categoryname, this.sotories});
      @override
      Widget build(BuildContext context) {
        return Container(
          child: Expanded(
            child: Column(
              children: [
                Text(categoryname),
                SizedBox(
                  height: 5,
                ),
                ListView.builder(
                  scrollDirection: Axis.vertical,
                  shrinkWrap: true,
                  itemCount: sotories.length,
                  itemBuilder: (context, index) => ListTile(
                    title: Text(sotories[index]['name']),
                    subtitle: Column(
                      children: [
                        Text(sotories[index]['phone_1']),
                        Text(sotories[index]['phone_2']),
                      ],
                    ),
                    trailing: CircleAvatar(
                      radius: 50,
                      backgroundImage: NetworkImage(sotories[index]['logo_url']),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      }
    }