I created this file json, I fetch the data like "displayName" and "age", also i want see on screen the data from the sublist workout. How can I do and if possibile put this data in a profile page?
this is the Json file i make for my little test db:
[
{
"displayName": "mario",
"age": 27,
"peso": 85,
"altezza": 175,
"workout": [
{
"nomeworkout": "Running"
},
{
"nomeworkout": "Brucia Grassi"
}
]
},
{
"displayName": "jessica",
"age": 28,
"peso": 85,
"altezza": 175,
"workout": [
{
"nomeworkout": "Spinning"
},
{
"nomeworkout": "Gambe"
}
]
},
{
"displayName": "Pedro",
"age": 29,
"peso": 85,
"altezza": 175,
"workout": [
{
"nomeworkout": "Potenziamento"
}
]
}
]
with this page, I created a simple ListView.builder to display the list of items such as "displayName", "age", "weight"; but I didn't understand how to get the data from the internal "workout" list:
import 'dart:convert';
import 'package:fitness_app/trainerPage.dart';
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List data;
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: FutureBuilder(
future:
DefaultAssetBundle.of(context).loadString('assets/jsonDb.json'),
builder: (context, snapshot) {
var data = JsonDecoder().convert(snapshot.data.toString());
return ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => TrainerPage()));
},
child: Container(
padding: EdgeInsets.all(10),
child: Row(
children: <Widget>[
Text(data[index]['displayName']),
Text(data[index]['age'].toString()),
],
),
),
);
},
);
},
),
),
);
}
}
simple future loader json
Future loadJson()async =>
[
{
"displayName": "mario",
"age": 27,
"peso": 85,
"altezza": 175,
"workout": [
{
"nomeworkout": "Running"
},
{
"nomeworkout": "Brucia Grassi"
}
]
},
{
"displayName": "jessica",
"age": 28,
"peso": 85,
"altezza": 175,
"workout": [
{
"nomeworkout": "Spinning"
},
{
"nomeworkout": "Gambe"
}
]
},
{
"displayName": "Pedro",
"age": 29,
"peso": 85,
"altezza": 175,
"workout": [
{
"nomeworkout": "Potenziamento"
}
]
}
];
simple view
class ContohLoadJson extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
child: FutureBuilder(
future: loadJson(),
builder: (context, snapshot){
List data = snapshot.data??[];
return data.isEmpty?Center(child: CircularProgressIndicator(),):
ListView(
children: List.generate(data.length, (index) =>
Card(
child: Container(
padding: EdgeInsets.all(8),
child: Column(
children: [
Row(
children: [
Text("Name : "),
Text(data[index]['displayName'])
],
),
Row(
children: [
Text("Age : "),
Text(data[index]['age'].toString())
],
),
Row(
children: [
Text("Peso : "),
Text(data[index]['peso'].toString())
],
),
Row(
children: [
Text("altezza: "),
Text(data[index]['altezza'].toString())
],
),
Column(
children: List.generate(data[index]['workout'].length, (index2) =>
Card(
child: Container(
padding: EdgeInsets.all(8),
child: Column(
children: [
Row(
children: [
Text("nomeworkout : "),
Text(data[index]['workout'][index2]['nomeworkout'])
],
)
],
),
),
)
).toList(),
)
],
),
),
)
).toList(),
);
},
)
);
}
}
you can extract the list like
var workouts = data[index]['workouts']
then iterate through that list to and render your views
Related
i have create quiz app, my question page is working properly but i want to display all wrong answers with their correct answers on the result page .I tried to get answers but give me so many errors. first i want display score then click show review answers to see the result page like this that u show on picture i want like this my score and result page
here is my question page
enter code here
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:quiz_app/controllers/profile_controllers.dart';
import 'package:quiz_app/widgets/common_components/appbar.dart';
import 'widgets/pallete.dart';
import 'widgets/rounded_button.dart';
void main() {
runApp(QuestionSample2());
}
class ChosenModel {
final int questionNumber;
final String questionAnswer;
ChosenModel(this.questionNumber, this.questionAnswer);
#override
String toString() {
return '{questionNumber: ${questionNumber}, questionAnswer: ${questionAnswer}}';
}
}
class QuestionControl extends GetxController {
List questions = [
{
"id": 1,
"question":
"Flutter is an open-source UI software development kit created by ______",
"options": ['Apple', 'Google', 'Facebook', 'Microsoft'],
"answer": "Google",
},
{
"id": 2,
"question": "When google release Flutter.",
"options": ['Jun 2017', 'July 2017', 'May 2017', 'May 2018'],
"answer": "Jun 2017",
},
{
"id": 3,
"question": "A memory location that holds a single letter or number.",
"options": ['Double', 'Int', 'Char', 'Word'],
"answer": "Char",
},
{
"id": 4,
"question": "What command do you use to output data to the screen?",
"options": ['Cin', 'Count', 'Cout', 'Output'],
"answer": "Output",
},
].obs;
List<ChosenModel> chosenAnswers = [];
RxList groupValue = [-1, 0, 5, 9, 13].obs;
RxList value = [
[0, 1, 2, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
].obs;
RxInt qnIndex = 1.obs;
}
class QuestionSample2 extends StatelessWidget {
QuestionSample2({Key? key}) : super(key: key);
final QuestionControl controller = Get.put(QuestionControl());
ProfileController _questionController = Get.put(ProfileController());
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: const Color.fromARGB(255, 0, 0, 0),
appBar: quizeAppbar(),
body: Padding(
padding: const EdgeInsets.fromLTRB(5, 15, 5, 10),
child: Column(
children: [
Obx(
() => Text(
controller.qnIndex.toString() +
'/' +
controller.questions.length.toString(),
style: Theme.of(context)
.textTheme
.headline4!
.copyWith(color: Colors.white)),
),
SizedBox(height: 20),
SizedBox(
height: 600.0,
child: PageView.builder(
itemCount: controller.questions.length,
onPageChanged: (pageNumber) {
controller.qnIndex.value = pageNumber + 1;
},
itemBuilder: (context, snapshot) {
var options = controller.questions[snapshot]['options'];
return Container(
margin: const EdgeInsets.fromLTRB(10, 0, 10, 0),
decoration: BoxDecoration(
color: const Color.fromARGB(255, 88, 79, 79),
borderRadius: BorderRadius.circular(15),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Spacer(
flex: 1,
),
Text(
controller.questions[snapshot]['question']
.toString(),
style: Theme.of(context)
.textTheme
.headline5!
.copyWith(color: Colors.white),
),
Spacer(
flex: 2,
),
Container(
height: 400.0,
child: ListView.builder(
itemCount: 4,
itemBuilder: (context, index) => ButtonBar(
alignment: MainAxisAlignment.center,
children: <Widget>[
Obx(
() => Container(
width: 300,
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
border: Border.all(
color: controller.groupValue[
snapshot] ==
controller.value[snapshot]
[index]
? kblue
: Color.fromARGB(
255, 117, 110, 110),
width: 2),
borderRadius:
BorderRadius.circular(15),
),
child: RadioListTile<int>(
activeColor: kblue,
title: Row(
children: [
Text(
options[index].toString(),
style: Theme.of(context)
.textTheme
.headline5!
.copyWith(
color: Colors.white),
),
Spacer(),
],
),
controlAffinity:
ListTileControlAffinity
.trailing,
groupValue:
controller.groupValue[snapshot],
value: controller.value[snapshot]
[index],
onChanged: (newValue) {
controller.groupValue[snapshot] =
newValue as int;
controller.chosenAnswers.add(
ChosenModel(
controller.questions[
snapshot]['id']
as int,
options[index]
.toString()));
print(controller.chosenAnswers);
}),
),
),
],
),
),
),
],
),
);
}),
),
Spacer(),
Obx(
() => controller.questions.length == controller.qnIndex.value
? const RoundedButton(
buttonName: 'Done',
page: '',
)
: Container(),
),
Spacer(),
],
),
),
),
);
}
}
enter code here
My Json response status code is 200 and the object is also created but when I try to bind it with UI in ListView it doesn't show anything. I have also parsed created the model from the json data.
Here's my API_manager.dart file:
import 'package:http/http.dart' as http;
import 'package:aritic/models/contactsModel.dart';
// ignore: camel_case_types
class API_Manager {
Future<ContactsModel> getContacts() async {
var client = http.Client();
var contactsModel;
String contacts_url =
'https://exampleapi.com';
String basicAuth = 'Basic auth key example';
try {
var response = await client.get(contacts_url,
headers: <String, String>{'authorization': basicAuth});
print(response.statusCode);
if (response.statusCode == 200) {
var jsonString = response.body;
var jsonMap = json.decode(jsonString);
contactsModel = contactsModel.fromJson(jsonMap);
}
} catch (Exception) {
return contactsModel;
}
return contactsModel;
}
}
My UI code:
import 'package:aritic/models/contactsModel.dart';
import 'package:aritic/services/api_manager.dart';
class ContactsPage extends StatefulWidget {
#override
_ContactsPageState createState() => _ContactsPageState();
}
class _ContactsPageState extends State<ContactsPage>
with SingleTickerProviderStateMixin {
Future<ContactsModel> _contactsModel;
bool isSearching = false;
TabController _tabController;
#override
void initState() {
// TODO: implement initState
super.initState();
_tabController = TabController(length: 2, initialIndex: 0, vsync: this);
_tabController.addListener(_handleTabIndex);
}
#override
void dispose() {
_tabController.removeListener(_handleTabIndex);
_tabController.dispose();
super.dispose();
}
void _handleTabIndex() {
setState(() {});
}
#override
Widget build(BuildContext context) {
_contactsModel = API_Manager().getContacts();
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: Text('Contacts'),
bottom: PreferredSize(
child: Align(
alignment: Alignment.centerLeft,
child: TabBar(
controller: _tabController,
isScrollable: true,
unselectedLabelColor: Colors.white.withOpacity(0.3),
indicatorColor: Colors.white,
tabs: [
Tab(
child: Text('Contacts'),
),
Tab(
child: Text('Companies'),
)
],
),
),
preferredSize: Size.fromHeight(40.0)),
actions: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 16.0),
child: IconButton(
icon: Icon(Icons.search),
color: Colors.white,
onPressed: () {},
),
),
],
),
body: TabBarView(controller: _tabController, children: <Widget>[
Container(
height: double.infinity,
child: FutureBuilder<ContactsModel>(
future: _contactsModel,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
padding: const EdgeInsets.all(6),
itemCount: snapshot.data.contacts.length,
itemBuilder: (context, index) {
var contact = snapshot.data.contacts[index];
return Container(
height: 100,
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(contact.owner.username,
style: TextStyle(fontSize: 16))
],
),
);
});
} else
return Center(child: CircularProgressIndicator());
})),
Container(
height: double.infinity,
child: ListView(
padding: const EdgeInsets.all(6),
children: <Widget>[
InkWell(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (_) => ViewCompany()));
},
child: Container(
height: 50,
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Example company',
style: TextStyle(fontSize: 16),
),
Text(
'Example company',
style: TextStyle(fontSize: 14),
)
],
),
),
),
SizedBox(
height: 5,
),
InkWell(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (_) => ViewCompany()));
},
child: Container(
height: 50,
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'example',
style: TextStyle(fontSize: 16),
),
Text(
'example',
style: TextStyle(fontSize: 14),
)
],
),
),
),
],
)),
]),
floatingActionButton: _bottomButtons(),
));
}
Widget _bottomButtons() {
return _tabController.index == 0
? FloatingActionButton(
shape: StadiumBorder(),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (_) {
return AddContacts();
}));
},
backgroundColor: Colors.cyan,
child: Icon(
Icons.person_add,
color: Colors.white,
))
: FloatingActionButton(
shape: StadiumBorder(),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (_) {
return AddCompany();
}));
},
backgroundColor: Colors.cyan,
child: Icon(
Icons.add,
color: Colors.white,
),
);
}
}
Output Screen:
ListView should be displayed here
Dart DevTools network analysis:
response code is displayed
Json Viewer:
Contacts Json
Json sample(complete json too big to upload here):
{
"total": "187144",
"contacts": {
"897": {
"isPublished": true,
"id": 897,
"fields": {
"core": {
"points": {
"id": "47",
"label": "Points"
},
"firstname": {
"id": "2",
"label": "First Name",
"value": "Jason"
},
"lastname": {
"id": "3",
"label": "Last Name",
"value": "Lamuda"
},
"...": {
"..." : "..."
}
},
"ipAddresses": [
{
"ip": "70.127.91.131",
"ipDetails": {
"city": "Bradenton",
"region": "Florida",
"timezone": "America/New_York",
}
},
"...": {
"..." : "..."
}
The JSON has this:
{
"total": "187144",
"contacts": {
"897": {
"isPublished": true,
"id": 897,
"fields": {
So your ContactModel.contacts is a Map keyed by the id values "897" etc, not a List, so this line returns null:
var contact = snapshot.data.contacts[index];
(This should throw an exception when you reference the members of contact.) You can index into the Map like this:
List keys = snapshot.data.contacts.keys.toList();
List values = snapshot.data.contacts.values.toList();
return ListView.builder(
padding: const EdgeInsets.all(6),
itemCount: snapshot.data.contacts.length,
itemBuilder: (context, index) {
var contact = values[index];
BTW this line in API_Manager is strange:
contactsModel = contactsModel.fromJson(jsonMap);
It gives a Null pointer exception. It should of course be:
contactsModel = ContactsModel.fromJson(jsonMap);
I want to display only the units with univ_spec_sub_id as 53 from the JSON returned into a Listview. I have tried implementing some code but it doesn't work. Is there any other way i can get the desired output?
This is the JSON being returned after hitting an URL :
"unit": [
{
"unit_id": "268",
"univ_spec_sub_id": "53",
"no_chapters": "13",
"unit_name": "File Handling and Dictionaries",
},
{
"unit_id": "300",
"univ_spec_sub_id": "53",
"no_chapters": "14",
"unit_name": "Decision Control Statements",
},
{
"unit_id": "298",
"univ_spec_sub_id": "59",
"no_chapters": "16",
"unit_name": "Electromagnetism",
},
{
"unit_id": "299",
"univ_spec_sub_id": "59",
"no_chapters": "0",
"unit_name": "Coming Soon",
},
This is the code i implemented.In this i have passed the unit JSON array as list and the univ_spec_sub_id using constructor:
checkid(int index){
if(widget.data[index]["univ_spec_sub_id"]== widget.univ_sub){
articles(index);
}
}
Container articles(int index){
return Container(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
GestureDetector(
child: Card(
child: Container(
child: Text(widget.data[index]["unit_no"]),
padding: const EdgeInsets.all(20),
),
),
onTap: (){
print(widget.univ_sub);
},)
],
),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.indigo[700],
body: ListView(
children: <Widget>[
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0, 10, 110, 0),
child: Container(
padding: EdgeInsets.fromLTRB(0, 30, 200, 0),
child: IconButton(icon: Icon(Icons.arrow_back),
color: Colors.black,
onPressed: (){
Navigator.pop(context);
},
),
),
),
SizedBox(height: 10,),
Text('Programming and ',
style: TextStyle(color: Colors.white,
fontSize: 32,
fontWeight: FontWeight.bold),
),
Text(' Problem Solving (IT) ',
style: TextStyle(color: Colors.white,
fontSize: 32,
fontWeight: FontWeight.bold),
),
],
),
SizedBox(height: 40,),
Container(
height: MediaQuery.of(context).size.height - 185,
decoration: BoxDecoration(
color: Colors.white70,
borderRadius: BorderRadius.only(topLeft: Radius.circular(75.0)),
),
child: Padding(
padding: EdgeInsets.fromLTRB(0, 100, 0, 0),
child: Expanded(
child: ListView.builder(
itemCount: widget.data.length,
itemBuilder: (BuildContext context,int index){
return Container(
child: checkid(index),
);
}),
),
),
)
],
),
);
Just check out the example that I have created.
json that you have given : Just validated from my side
{
"unit": [{
"unit_id": "268",
"univ_spec_sub_id": "53",
"no_chapters": "13",
"unit_name": "File Handling and Dictionaries"
},
{
"unit_id": "300",
"univ_spec_sub_id": "53",
"no_chapters": "14",
"unit_name": "Decision Control Statements"
},
{
"unit_id": "298",
"univ_spec_sub_id": "59",
"no_chapters": "16",
"unit_name": "Electromagnetism"
},
{
"unit_id": "299",
"univ_spec_sub_id": "59",
"no_chapters": "0",
"unit_name": "Coming Soon"
}
]
}
This is t the model class for the json
// To parse this JSON data, do
//
// final unit = unitFromJson(jsonString);
import 'dart:convert';
Unit unitFromJson(String str) => Unit.fromJson(json.decode(str));
String unitToJson(Unit data) => json.encode(data.toJson());
class Unit {
Unit({
this.unit,
});
List<UnitElement> unit;
factory Unit.fromJson(Map<String, dynamic> json) => Unit(
unit: List<UnitElement>.from(json["unit"].map((x) => UnitElement.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"unit": List<dynamic>.from(unit.map((x) => x.toJson())),
};
}
class UnitElement {
UnitElement({
this.unitId,
this.univSpecSubId,
this.noChapters,
this.unitName,
});
String unitId;
String univSpecSubId;
String noChapters;
String unitName;
factory UnitElement.fromJson(Map<String, dynamic> json) => UnitElement(
unitId: json["unit_id"],
univSpecSubId: json["univ_spec_sub_id"],
noChapters: json["no_chapters"],
unitName: json["unit_name"],
);
Map<String, dynamic> toJson() => {
"unit_id": unitId,
"univ_spec_sub_id": univSpecSubId,
"no_chapters": noChapters,
"unit_name": unitName,
};
}
This is the main ui for it :
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:json_parsing_example/models.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primarySwatch: Colors.amber),
home: FirstPage(),
);
}
}
class FirstPage extends StatefulWidget {
#override
_FirstPageState createState() => _FirstPageState();
}
class _FirstPageState extends State<FirstPage> {
List<UnitElement> unitList = List();
#override
void initState() {
super.initState();
loadData();
}
Future<String> loadFromAssets() async {
return await rootBundle.loadString('json/parse.json');
}
loadData() async {
String jsonString = await loadFromAssets();
final unit = unitFromJson(jsonString);
unitList = unit.unit;
}
#override
Widget build(BuildContext context) {
return Container(
child: RaisedButton(
child: Text('Second'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondPage(
data: unitList,
univ_sub: "53",// This 53 is hardcoded you can add as per //your code
),
),
);
},
),
);
}
}
class SecondPage extends StatefulWidget {
final String univ_sub;
final List<UnitElement> data;
const SecondPage({Key key, this.univ_sub, this.data}) : super(key: key);
#override
_SecondPageState createState() => _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
Widget checkid(int index) {
if (widget.data[index].univSpecSubId == widget.univ_sub) {
return articles(index);
}
}
Container articles(int index) {
return Container(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
GestureDetector(
child: Card(
child: Container(
child: Text(widget.data[index].unitId),
padding: const EdgeInsets.all(20),
),
),
onTap: () {
print(widget.univ_sub);
},
)
],
),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.indigo[700],
body: ListView(
children: <Widget>[
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(0, 10, 110, 0),
child: Container(
padding: EdgeInsets.fromLTRB(0, 30, 200, 0),
child: IconButton(
icon: Icon(Icons.arrow_back),
color: Colors.black,
onPressed: () {
Navigator.pop(context);
},
),
),
),
SizedBox(
height: 10,
),
Text(
'Programming and ',
style: TextStyle(
color: Colors.white,
fontSize: 32,
fontWeight: FontWeight.bold),
),
Text(
' Problem Solving (IT) ',
style: TextStyle(
color: Colors.white,
fontSize: 32,
fontWeight: FontWeight.bold),
),
],
),
SizedBox(
height: 40,
),
Container(
height: MediaQuery.of(context).size.height - 185,
decoration: BoxDecoration(
color: Colors.white70,
borderRadius: BorderRadius.only(topLeft: Radius.circular(75.0)),
),
child: Padding(
padding: EdgeInsets.fromLTRB(0, 100, 0, 0),
child: ListView.builder(
shrinkWrap: true,
itemCount: widget.data.length,
itemBuilder: (BuildContext context, int index) {
return Container(
child: checkid(index),
);
}),
),
)
],
),
);
}
}
Just check it out and let me know if it works.
How to parse the JSON to list in flutter. I have used the online tool to parse the Json, but the tool is converting it to the map. I need to get the parsed json in the list and return the list of contents in listview builder of the page. I have my json file and my workaround below.
Json
{
"batchcomplete": "",
"continue": {
"gcmcontinue": "page|41434143494120464552525547494e4541202d204152494d45444148|3704",
"continue": "gcmcontinue||"
},
"query": {
"pages": {
"225": {
"pageid": 225,
"ns": 0,
"title": "Abrus precatorius - Gunja",
"thumbnail": {
"source": "https://example.org/images/thumb/c/cb/Abrus_precatorius_%281463017430%29.jpg/600px-Abrus_precatorius_%281463017430%29.jpg",
"width": 600,
"height": 450
},
"pageimage": "Abrus_precatorius_(1463017430).jpg"
},
"625": {
"pageid": 625,
"ns": 0,
"title": "Abies webbiana - Talispatra",
"thumbnail": {
"source": "https://example.org/images/thumb/b/b1/Red_fir.jpg/397px-Red_fir.jpg",
"width": 397,
"height": 600
},
"pageimage": "Red_fir.jpg"
},
"15995": {
"pageid": 15995,
"ns": 0,
"title": "Abelmoschus esculentus - Bhenda",
"thumbnail": {
"source": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d0/India_-_Koyambedu_Market_-_Ladies_Finger_03_%283986242135%29.jpg/600px-India_-_Koyambedu_Market_-_Ladies_Finger_03_%283986242135%29.jpg",
"width": 600,
"height": 450
},
"pageimage": "India_-_Koyambedu_Market_-_Ladies_Finger_03_(3986242135).jpg"
}
}
},
"limits": {
"pageimages": 500
}
}
Herbslist.dart
class Herbs extends StatefulWidget {
final String title;
Herbs(this.title);
#override
_HerbsState createState() => new _HerbsState();
}
class _HerbsState extends State<Herbs> {
var cname;
Future<Herbslist> fetchPost() async {
final response = await http.get(
'https://example.org/api.php?action=query&gcmtitle=Category:$cname&pilimit=max&prop=pageimages&pithumbsize=600&generator=categorymembers&format=json&gcmcontinue='
);
if (response.statusCode == 200) {
if(this.mounted){
return Herbslist.fromJson(json.decode(response.body));
}
} else {
print(Exception);
throw (e) {
print("Exception thrown: $e");
Exception(e);
};
}
}
#override
Widget build(BuildContext context) {
cname = widget.title;
return new Scaffold(
appBar: AppBar(
title: Align(
alignment: Alignment(-0.2, 0.3),
child: Text(
cname,
),
),
),
body: Center(
child: FutureBuilder<Herbslist>(
future: fetchPost(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.query.pages.length,
itemBuilder: (BuildContext context, int index) {
// var gcm = snapshot.data.herbslistContinue.gcmcontinue;
var img = snapshot.data.query.pages.values
.toList()[index]
.thumbnail
.source;
return Container(
child: Card(
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Detailpage(
snapshot.data.query.pages.values
.toList()[index]
.title,
),
));
},
child: ListTile(
contentPadding: EdgeInsets.symmetric(
horizontal: 8.0, vertical: 8.0),
leading: Container(
padding: EdgeInsets.only(right: 10.0),
decoration: new BoxDecoration(
border: new Border(
right: new BorderSide(
width: 1.5, color: Colors.grey)),
),
// ignore: unrelated_type_equality_checks
child: img == img.isEmpty
? SizedBox(
height: 50.0,
width: 50.0,
child: Image.asset('image.png'),
)
: SizedBox(
height: 50.0,
width: 50.0,
child: FadeInImage.assetNetwork(
placeholder: 'image.png',
image: img,
fit: BoxFit.fill,
),
)),
title: Text(snapshot.data.query.pages.values
.toList()[index]
.title),
),
)));
},
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
));
}
}
[1]: https://app.quicktype.io/
You can do something as simple as this, assuming the variable jsonMap is the json you showed above:
jsonMap['query']['pages'].values.toList()
Edit: Edited to change to better solution suggested in the comments.
Here is an example of how you could apply it on your code:
FutureBuilder<Herbslist>(
future: fetchPost(),
builder: (context, snapshot) {
if (snapshot.hasData) {
List pages = snapshot.data['query']['pages'].values.toList();
return ListView.builder(
shrinkWrap: true,
itemCount: pages.length,
Make sure to change the rest of your code to use the new pages variable.
this json has two data first only name and second is inside there also name which is service name. ex 'Travel and Stay' and 'Religious' is main name which has to be displayed in expansion tile name and The 'Church/ Baptism' and 'Hindu Temples' is a subitem which is displayed inside checkbox list tile. Hope you understand :slightly_smiling_face: Please Help me
class _MyHomePageState extends State<MyHomePage> {
var lovCountryServices = [
{
"services": [
{
"service_group_id": 22,
"service_category": "B",
"name": "Air Tickets",
"id": 228
},
{
"service_group_id": 22,
"service_category": "W",
"name": "Boys Hostel",
"id": 229
},
],
"name": "Travel and Stay",
"is_active": true,
"id": 22
},
{
"services": [
{
"service_group_id": 19,
"service_category": "B",
"name": "Church/ Baptism",
"id": 193
},
{
"service_group_id": 19,
"service_category": "B",
"name": "Hindu Temples",
"id": 194
}
],
"name": "Religious",
"is_active": true,
"id": 19
}
];
List<_Result> _results = [];
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
children: <Widget>[
ListView.builder(
shrinkWrap: true,
padding: const EdgeInsets.all(8.0),
itemCount: lovCountryServices.length,
itemBuilder: (BuildContext context, int index) {
var item = lovCountryServices[index];
var items= lovCountryServices[index]['services'];
return ExpansionTile(
title: Text(item['name']),
children: <Widget>[
CheckboxListTile(
title: Text("temp"),
value: item['is_active'],
onChanged: (val) {
setState(() {
item['is_active'] = val;
});
},
),
],
);
},
),
RaisedButton(
onPressed: () => print("sending to backend"),
child: Text("SEND"),
)
],
)),
);
}
}
I want thw data in checkbox list tile right there is dummy data called TEMP and i want the data from json right now in json there is 'Boys Hostel' this data needs to comes inside the checkbox listtile. Hope you undestand please help me
Working Code: You can use a Map variable to store boolean value.
Map<String, bool> _selection = {};
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dummy'),
),
body: Center(
child: Column(
children: <Widget>[
ListView.builder(
shrinkWrap: true,
padding: const EdgeInsets.all(8.0),
itemCount: lovCountryServices.length,
itemBuilder: (BuildContext context, int index) {
var item =
lovCountryServices[index]; // should be outside build function
List items = item['services']; // should be outside build function
return ExpansionTile(
title: Text(item['name']),
children: List.generate(items.length, (i) {
_selection[items[i]['name']] =
_selection[items[i]['name']] ?? item['is_active'];
return CheckboxListTile(
title: Text(items[i]['name']),
value: _selection[items[i]['name']],
onChanged: (val) {
setState(() {
_selection[items[i]['name']] = val;
});
},
);
}),
);
},
),
RaisedButton(
onPressed: () => print("sending to backend"),
child: Text("SEND"),
)
],
)),
);
}