skip to Main Content

my getting json response as

{
    "cities": [
        {
            "CTID": "5",
            "City": "Hatkanangle",
            "Status": "1"
        },
        {
            "CTID": "6",
            "City": "Sangli",
            "Status": "1"
        },
        {
            "CTID": "7",
            "City": "Ichalkaranji",
            "Status": "1"
        },
        {
            "CTID": "8",
            "City": "Shirol",
            "Status": "1"
        }
    ],
    "status": 200,
    "message": "data found!"
}

how can i use this data in listview builder,
i want to display list of cities after selecting city onpressed i want to save id of the perticular city in a variable,

4

Answers


  1. Firstly, create a class model file city_model.dart

    class City {
      final String ctid;
      final String name;
      final String status;
    
      City({required this.ctid, required this.name, required this.status});
    
      factory City.fromJson(Map<String, dynamic> json) {
        return City(
          ctid: json['CTID'] as String,
          name: json['City'] as String,
          status: json['Status'] as String,
        );
      }
    }
    

    Use this to decode json data and implement in listview.builder

      Map<String, dynamic> map = json.decode(jsonData); //jsonData is your json response
            var cityList = (map['cities'] as List)
                .map((value) => City.fromJson(value))
                .toList(); 
    
        //And then add it to listview.builder
    
      ListView.builder(
            itemCount: cityList.length,
            itemBuilder: (context, index) {
              final city = cityList[index];
              
            return ListTile(
                title: Text(city.name),
                subtitle: Text('ID: ${city.ctid}, Status: ${city.status}'),
                onTap: () {
                   // val = city.ctid; 
               },
               ),
            },
      );
    
    Login or Signup to reply.
  2. First of all you should parse the list into a list variable then use this variable in the ListView builder.

    you can define a model like that

    class City {
      final String ctid;
      final String name;
      final String status;
    
      City({required this.ctid, required this.name, required this.status});
    
      factory City.fromJson(Map<String, dynamic> json) {
        return City(
          ctid: json['CTID'],
          name: json['City'],
          status: json['Status'],
        );
      }
    }
    
    

    and use it in your widget

    import 'package:flutter/material.dart';
    import 'dart:convert';
    import 'package:http/http.dart' as http;
    
    class CityListPage extends StatefulWidget {
      @override
      _CityListPageState createState() => _CityListPageState();
    }
    
    class _CityListPageState extends State<CityListPage> {
      // define List var
      late List<City> cities;
    
      @override
      void initState() {
        super.initState();
        // call your API
        fetchData();
      }
    
      Future<void> fetchData() async {
        final response = await http.get(Uri.parse('YOUR_API_ENDPOINT'));
        if (response.statusCode == 200) {
          // keep your response body in a variable 
          final parsed = jsonDecode(response.body);
          // use cities field from the response to parse data from the json
          List<dynamic> cityList = parsed['cities'];
          // use the model to map each City
          cities = cityList.map((json) => City.fromJson(json)).toList();
        } else {
          throw Exception('Failed to load data');
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('City List'),
          ),
          body: cities == null
              ? Center(child: CircularProgressIndicator())
              : ListView.builder(
                  itemCount: cities.length,
                  itemBuilder: (context, index) {
                    final city = cities[index];
                    return ListTile(
                      title: Text(city.name),
                      subtitle: Text('Status: ${city.status}'),
                    );
                  },
                ),
        );
      }
    }
    
    
    Login or Signup to reply.
  3. First you need to create a model:

    // To parse this JSON data, do
    //
    //     final cityResponseModel = cityResponseModelFromJson(jsonString);
    
    import 'dart:convert';
    
    CityResponseModel cityResponseModelFromJson(String str) => CityResponseModel.fromJson(json.decode(str));
    
    String cityResponseModelToJson(CityResponseModel data) => json.encode(data.toJson());
    
    class CityResponseModel {
        List<City> cities;
        int status;
        String message;
    
        CityResponseModel({
            required this.cities,
            required this.status,
            required this.message,
        });
    
        factory CityResponseModel.fromJson(Map<String, dynamic> json) => CityResponseModel(
            cities: List<City>.from(json["cities"].map((x) => City.fromJson(x))),
            status: json["status"],
            message: json["message"],
        );
    
        Map<String, dynamic> toJson() => {
            "cities": List<dynamic>.from(cities.map((x) => x.toJson())),
            "status": status,
            "message": message,
        };
    }
    
    class City {
        String ctid;
        String city;
        String status;
    
        City({
            required this.ctid,
            required this.city,
            required this.status,
        });
    
        factory City.fromJson(Map<String, dynamic> json) => City(
            ctid: json["CTID"],
            city: json["City"],
            status: json["Status"],
        );
    
        Map<String, dynamic> toJson() => {
            "CTID": ctid,
            "City": city,
            "Status": status,
        };
    }
    

    Then your page like this:

    class MyHomePage extends StatefulWidget {
      const MyHomePage({super.key,});
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
    
      CityResponseModel cityResponse=CityResponseModel(cities: [], status: 0, message: "");
      City? selectedCity ;
      void fetchData() {
        setState(() {
          //fetch city list here
        });
      }
    
      @override
      void initState() {
    fetchData();
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        
        return Scaffold(
          appBar: AppBar(
            
            backgroundColor: Theme.of(context).colorScheme.inversePrimary,
           
            title: Text("City"),
          ),
          body: ListView.builder(
            itemCount:  cityResponse.cities.length,
            itemBuilder: (context, index) => GestureDetector(
              onTap: (){
                setState(() {
                  //You must change with your logics
                selectedCity=cityResponse.cities[index];
                });
              },
              child: Column(
                children: [
                  Text(cityResponse.cities[index].city),
                  Text(cityResponse.cities[index].ctid),
                  Text(cityResponse.cities[index].status),
                ],
              ),
            ),
          ));
      }
    }
    
    Login or Signup to reply.
  4. We can show city names using this way

    First create empty list

    List<dynamic> cities = [];
    

    Then decode jsondata using json.decode. Simply add this two line code in initState

    final Map<String, dynamic> data = json.decode(jsonData);
    cities = data['cities'];
    

    Then after you can use cities list in ListView.builder

    ListView.builder(
                  itemCount: cities.length,
                    itemBuilder: (context, index) {
                      var cityName = cities[index]['City'];
                      return Text('$cityName');
                    },
                )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search