0

I am creating the page having the drop-down and list view. Now I am showing full data in the list view. If I want to have any particular date data then what I need to do. Please help me to resolve this. Below is the JSON I am fetching.

 

    {
        "data": [{
                "Date": "2019-07-08",
                "Details": [{
                    "id": 1
                }, {
                    "id": 2
                }]
            },
            {
                "Date": "2019-07-09",
                "Details": [{
                    "id": 3
                }, {
                    "id": 4
                }]
            },
            {
                "Date": "2019-07-10",
                "Details": [{
                    "id": 5
                }, {
                    "id": 6
                }]
            }

        ]
    }

Below is the code

    Future getData() async {
        var response = await http.get(
            Uri.encodeFull(url),
            headers: {
                "Accept": "application/json"
            }
        );
        setState(() {
            var extractdata = jsonDecode(response.body);
            data = extractdata["data"];
        });
        return 'success';
    }

    Column(
        children: [
            Expanded(
                child: Container(
                    color: Colors.greenAccent,
                    child: ListView.builder(
                        itemCount: data == null ? 0 : data.length,
                        shrinkWrap: true,
                        itemBuilder: (context, index) {                    
                            return ListView.builder(
                                shrinkWrap: true,
                                physics: NeverScrollableScrollPhysics(),
                                itemCount: data == null ? 0 : data[index]["Session_Details"].length,
                                itemBuilder: (context, i) {
                                    return ListTile(title: Text("id"));
                                }
                            );
                        }
                    ),
                )
            ),
        ]
    )

2 Answers 2

2

You can copy paste run full code below
You can compare selected dropdown value and show only specific data
and return Container() (don't display) for others
code snippet

ListView.builder(
      itemCount: payload == null ? 0 : payload.data.length,
      shrinkWrap: true,
      itemBuilder: (context, index) {
        return ListView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemCount: payload == null
                ? 0
                : payload.data[index].details.length,
            itemBuilder: (context, i) {
              if (dropdownValue == null) {
                return ListTile(
                    title: Text(
                        "${payload.data[index].details[i].id}"));
              } else {
                if (payload.data[index] == dropdownValue) {
                  return ListTile(
                      title: Text(
                          "${payload.data[index].details[i].id}"));
                } else {
                  return Container();
                }
              }
            });
      }),

working demo

enter image description here

full code

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// To parse this JSON data, do
//
//     final payload = payloadFromJson(jsonString);

import 'dart:convert';

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
  List<Datum> data;

  Payload({
    this.data,
  });

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
      };
}

class Datum {
  DateTime date;
  List<Detail> details;

  Datum({
    this.date,
    this.details,
  });

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        date: DateTime.parse(json["Date"]),
        details:
            List<Detail>.from(json["Details"].map((x) => Detail.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "Date":
            "${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}",
        "Details": List<dynamic>.from(details.map((x) => x.toJson())),
      };
}

class Detail {
  int id;

  Detail({
    this.id,
  });

  factory Detail.fromJson(Map<String, dynamic> json) => Detail(
        id: json["id"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
      };
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Payload payload;
  Datum dropdownValue = null;

  Future getData() async {
    var response = await http
        .get("https://www.json-generator.com/api/json/get/bOpGzigKOG?indent=2");
    payload = payloadFromJson(response.body);

    setState(() {});
    return 'success';
  }

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getData();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: payload == null
          ? CircularProgressIndicator()
          : Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Center(
                    child: DropdownButton<Datum>(
                      //isDense: true,
                      hint: Text('Choose'),
                      value: dropdownValue,
                      icon: Icon(Icons.check_circle_outline),
                      iconSize: 24,
                      elevation: 16,
                      style: TextStyle(color: Colors.deepPurple),
                      underline: Container(
                        height: 2,
                        color: Colors.blue[300],
                      ),
                      onChanged: (Datum newValue) {
                        setState(() {
                          dropdownValue = newValue;
                        });
                      },
                      items: payload.data
                          .map<DropdownMenuItem<Datum>>((Datum value) {
                        return DropdownMenuItem<Datum>(
                            value: value,
                            child: Text(
                                ' ${value.date.year.toString()}/${value.date.month.toString()}/${value.date.day.toString()}'));
                      }).toList(),
                    ),
                  ),
                  ListView.builder(
                      itemCount: payload == null ? 0 : payload.data.length,
                      shrinkWrap: true,
                      itemBuilder: (context, index) {
                        return ListView.builder(
                            shrinkWrap: true,
                            physics: NeverScrollableScrollPhysics(),
                            itemCount: payload == null
                                ? 0
                                : payload.data[index].details.length,
                            itemBuilder: (context, i) {
                              if (dropdownValue == null) {
                                return ListTile(
                                    title: Text(
                                        "${payload.data[index].details[i].id}"));
                              } else {
                                if (payload.data[index] == dropdownValue) {
                                  return ListTile(
                                      title: Text(
                                          "${payload.data[index].details[i].id}"));
                                } else {
                                  return Container();
                                }
                              }
                            });
                      }),
                  Text(
                    'You have pushed the button this many times:',
                  ),
                  Text(
                    '$_counter',
                    style: Theme.of(context).textTheme.headline4,
                  ),
                ],
              ),
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Glad to help, please mark this as answer if it helps. thanks.
i tried with ur code is working. But if i fetch the json from api, then i am getting error(Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'). [link]json-generator.com/api/json/get/bOpGzigKOG?indent=2. i am fetching the json from the above url.
` var response = await http.get( "json-generator.com/api/json/get/bOpGzigKOG?indent=2"); var extractdata = jsonDecode(response.body); print(response); payload = payloadFromJson(extractdata);`
please help me for this. Thanks
just use -> var response = await http.get("json-generator.com/api/json/get/bOpGzigKOG?indent=2"); payload = payloadFromJson(response.body);
0
var json = JsonDecoder().convert(response.body);
        List <String> a = [];
        json.map((value) {
          a.add(value["key"]);
}).toList();

print(_phoneCodeList.runtimeType);

/* I/flutter (14165): List */

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.