I want to fetch data from the JSON file to GridView.builder(), I watched a lot of videos but I didn't achieve any results, please help me to do that.
This is the JSON file I want to use: My JSON file here
{
"Ads": {
"show_ads": true,
"InterAd": "unity",
"bannerAd": "unity",
},
"LOCAL_BANNER": {
"show": true,
"image": "image1.jpg",
"url": "https://www.google.com"
},
"MORE_APPS": [{
"title": "Get app now",
"img": "www.google.com",
"url": "www.google.com",
"country": "IN"
}, {
"title": "Get app now",
"img": "www.google.com",
"url": "www.google.com",
"country": ""
}
],
}
I WANT TO fill data to grid view using MORE_APPS key.
Thank you;
1st.. store your json in an asset folder.. preferribly in rootfolder/assets
2.. register your asset in your pubspec.yaml file
3.. create your model.. preferribly using https://app.quicktype.io/dart/.. copy your json data there, and it will generate your model for you.
// To parse this JSON data, do
//
// final myData = myDataFromJson(jsonString);
import 'dart:convert';
MyData myDataFromJson(String str) => MyData.fromJson(json.decode(str));
String myDataToJson(MyData data) => json.encode(data.toJson());
class MyData {
MyData({
this.ads,
this.localBanner,
this.moreApps,
});
Ads? ads;
LocalBanner? localBanner;
List<MoreApp>? moreApps;
factory MyData.fromJson(Map<String, dynamic> json) => MyData(
ads: Ads.fromJson(json["Ads"]),
localBanner: LocalBanner.fromJson(json["LOCAL_BANNER"]),
moreApps: List<MoreApp>.from(json["MORE_APPS"].map((x) => MoreApp.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Ads": ads!.toJson(),
"LOCAL_BANNER": localBanner!.toJson(),
"MORE_APPS": List<dynamic>.from(moreApps!.map((x) => x.toJson())),
};
}
class Ads {
Ads({
this.showAds,
this.interAd,
this.bannerAd,
});
bool? showAds;
String? interAd;
String? bannerAd;
factory Ads.fromJson(Map<String, dynamic> json) => Ads(
showAds: json["show_ads"],
interAd: json["InterAd"],
bannerAd: json["bannerAd"],
);
Map<String, dynamic> toJson() => {
"show_ads": showAds,
"InterAd": interAd,
"bannerAd": bannerAd,
};
}
class LocalBanner {
LocalBanner({
this.show,
this.image,
this.url,
});
bool? show;
String? image;
String? url;
factory LocalBanner.fromJson(Map<String, dynamic> json) => LocalBanner(
show: json["show"],
image: json["image"],
url: json["url"],
);
Map<String, dynamic> toJson() => {
"show": show,
"image": image,
"url": url,
};
}
class MoreApp {
MoreApp({
this.title,
this.img,
this.url,
this.country,
});
String? title;
String? img;
String? url;
String? country;
factory MoreApp.fromJson(Map<String, dynamic> json) => MoreApp(
title: json["title"],
img: json["img"],
url: json["url"],
country: json["country"],
);
Map<String, dynamic> toJson() => {
"title": title,
"img": img,
"url": url,
"country": country,
};
}
4.. create your function that converts the json data to the model..
import 'package:flutter/services.dart';
Future<MyData> readJsonFile() async {
final String response = await rootBundle.loadString('assets/filejson.json');
final data = myDataFromJson(response);
return data;
}
5.. declare a global variable.. in this case i have named the model MyData.. so declare that globally
MyData data = MyData();
in your initstate make sure to assign your value to the variable data
void initState() {
readJsonFile().then((value) => setState((){
data = value;
}));
super.initState();}
then do the following
FutureBuilder(
future: readJsonFile(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if(snapshot.hasData){
return Center(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
color: Colors.lightGreen,
child: Column(
children: [
Text(
"Ads"
),
Text("show_ads: ${data.ads!.showAds}"),
Text("InterAd : ${data.ads!.interAd}"),
Text("bannerAd: ${data.ads!.bannerAd}")
],
),
),
Container(
color: Colors.amber,
child: Column(
children: [
Text(
"LOCAL_BANNER"
),
Text("show: ${data.localBanner!.show}"),
Text("image: ${data.localBanner!.image}"),
Text("url: ${data.localBanner!.url}"),
],
),
)
],
),
SizedBox(height: 40,),
Expanded(
child: GridView.builder(
itemCount: data.moreApps!.length,
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
childAspectRatio: 3 / 2,
crossAxisSpacing: 20,
mainAxisSpacing: 20),
itemBuilder: (context, index) {
return Container(
child: Column(
children: [
Text(data.moreApps![index].title!),
Text(data.moreApps![index].img!),
Text(data.moreApps![index].url!),
Text(data.moreApps![index].country!),
],
),
);
}),
),
],
)
); }
else{
return const CircularProgressIndicator();
}
},)
Related
I am developing an android application with flutter, what I am doing is displaying a json in an application page. When I run the application it doesn't give me an error but it doesn't show me the data, the json I want to read is the following:
[
{
"deviceid": 27,
"f2cuid": "Estacion1_A",
"devicedata": {
"isRunning": 0,
"color": "w3-red",
"colorNoW3": "red",
"device_name": "Estacion1_A"
}
},
{
"deviceid": 20,
"f2cuid": "B19",
"devicedata": {
"isRunning": 1,
"color": "w3-green",
"colorNoW3": "green",
"device_name": "B19"
}
}
]
It's in my model class:
class Stations {
Int? isRunning;
String? color;
String? colorNoW3;
String? devicename;
Stations(
{this.isRunning,
this.color,
this.colorNoW3,
this.devicename,
});
factory Stations.fromJson(Map<String, dynamic> json) {
return Stations(
isRunning: json['isRunning'],
color: json['color'],
colorNoW3: json['colorNoW3'],
devicename: json['device_name'],
);
}
}
This is my service:
Future<List<Stations>> getStations() async {
Uri url = Uri.parse('URL');
final response = await http.get(url);
var data = jsonDecode(response.body);
print('data: $data');
List<Stations> stations = data.map((e) => Stations.fromJson(e)).toList();
return stations;
}
and this is the way I display it:
return Scaffold(
appBar: AppBar(
title: const Text('Sistema Escolar Administrativo'),
),
drawer: DrawerWidgetMenu(),
body: Container(
child: FutureBuilder(
future: stationSvc.getStations(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Container(
child: Center(
child: Text('No hay datos que mostrar'),
),
);
}
return snapshot.data.length > 0
? ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: InkWell(
onTap: () {
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => HomePage(),
),
);
},
child: ListTile(
leading: Text(snapshot.data[index].devicename!),
title: Text(snapshot.data[index].color!),
subtitle: Text(snapshot.data[index].colorNoW3!),
),
));
})
: Center(
child: Text('No hay datos, registra un grupo primero'));
}),
),
);
You forgot to specify nested map:
factory Stations.fromJson(Map<String, dynamic> json) {
return Stations(
isRunning: json['devicedata']?['isRunning'],
color: json['devicedata']?['color'],
colorNoW3: json['devicedata']?['colorNoW3'],
devicename: json['devicedata']?['device_name'],
);
}
I am sharing a complete class named SampleModel below which can help to parse JSON in flutter:
class SampleModel {
String? _myName;
bool? _isActive;
SampleModel({String? myName, bool? isActive}) {
if (myName != null) {
_myName = myName;
}
if (isActive != null) {
_isActive = isActive;
}
}
String? get myName => _myName;
set myName(String? myName) => _myName = myName;
bool? get isActive => _isActive;
set isActive(bool? isActive) => _isActive = isActive;
SampleModel.fromJson(Map<String, dynamic> json) {
_myName = json['myName'];
_isActive = json['isActive'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['myName'] = _myName;
data['isActive'] = _isActive;
return data;
}
}
Sample JSON for the same class:
{
"myName" : "Your Name",
"isActive" : true
}
Check if this can help in your case.
your json type is an array, not a map.
look at [ ] syntax on json file.
to deal with an Array, you should make it to a list first:
List<Map<String,dynamic>> mylistofMapformJson = json.decode(receivedJson);
//you should get your list stations like this:
List<Stations> listStationsFromJson = List.generate(
mylistofMapformJson.length,
(index) => Stations.fromJson(mylistofMapformJson));
I need help integrating the Rest API data response into my graph.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:http/http.dart' as http;
class GraphData {
final String year;
final int clicks;
final charts.Color color;
GraphData(this.year, this.clicks, Color color)
: this.color = charts.Color(
r: color.red, g: color.green, b: color.blue, a: color.alpha);
}
class Bargraph extends StatelessWidget {
const Bargraph({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
var data = [
GraphData('A', 1242558, Colors.orange),
GraphData('B', 4280940, Colors.orange),
GraphData('C', 2942064, Colors.orange),
];
var series = [
charts.Series(
domainFn: (GraphData clickData, _) => clickData.year,
measureFn: (GraphData clickData, _) => clickData.clicks,
colorFn: (GraphData clickData, _) => clickData.color,
id: 'Graph',
data: data,
),
];
var chart = charts.BarChart(
series,
animate: true,
);
var chartWidget = Padding(
padding: EdgeInsets.all(0.0),
child: Container(
height: 200.0,
width: 350,
child: chart,
),
);
return Column(
children: [chartWidget],
);
}
}
The above code was a static graph I am using. But I need to pass the Rest API array data into my graph.
{
"status": true,
"message": "Graph Result",
"result": {
"graph-data": [
{
"name": "Graph A",
"value": 661041,
},
{
"name": "Graph B",
"value": 2277460,
},
{
"name": "Graph C",
"value": 1565178,
} ]
}
}
It's my Rest API data response.
The following is my API call, How do I pass the response array data into a graph.
Future<Map<String, dynamic>> apicall() async {
// String propid = widget.value.propid;
//print(propid);
var headers = {
'Authorization':
'',
'Cookie': ''
};
var request = http.MultipartRequest(
'POST', Uri.parse('***************'));
request.fields.addAll({
});
request.headers.addAll(headers);
var streamedResponse = await request.send();
var response = await http.Response.fromStream(streamedResponse);
final result = jsonDecode(response.body) as Map<String, dynamic>;
if (response.statusCode == 200) {
print("result");
}
} else {
print("called error");
print(response.reasonPhrase);
}
return result["result"];
}
The following is my class model, How to use this model and response data to integrate graph
import 'dart:convert';
List<Graphmodel> graphmodelFromJson(String str) => List<Graphmodel>.from(json.decode(str).map((x) => Graphmodel.fromJson(x)));
String graphmodelToJson(List<Graphmodel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Graphmodel {
Graphmodel({
this.name,
this.value,
});
String name;
int value;
factory Graphmodel.fromJson(Map<String, dynamic> json) => Graphmodel(
name: json["name"],
value: json["value"],
);
Map<String, dynamic> toJson() => {
"name": name,
"value": value,
};
}
I am facing some issues while integrating API array data to display a graph. so anyone can help me to solve the issue.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:charts_flutter/charts_flutter.dart' as charts;
import 'package:http/http.dart' as http;
class GraphData {
final String year;
final int clicks;
final charts.Color color;
GraphData(this.year, this.clicks, Color color)
: this.color = charts.Color(
r: color.red, g: color.green, b: color.blue, a: color.alpha);
}
class Bargraph extends StatelessWidget {
const Bargraph({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
// var data = [
// GraphData('A', 1242558, Colors.orange),
// GraphData('B', 4280940, Colors.orange),
// GraphData('C', 2942064, Colors.orange),
// ];
var data = apiResponse['result']['graph-
data'].entries.map((e)=>GraphData(e['name'],e['value'], Colors.orange))
var series = [
charts.Series(
domainFn: (GraphData clickData, _) => clickData.year,
measureFn: (GraphData clickData, _) => clickData.clicks,
colorFn: (GraphData clickData, _) => clickData.color,
id: 'Graph',
data: data,
),
];
var chart = charts.BarChart(
series,
animate: true,
);
var chartWidget = Padding(
padding: EdgeInsets.all(0.0),
child: Container(
height: 200.0,
width: 350,
child: chart,
),
);
return Column(
children: [chartWidget],
);
}
}
final apiResponse = {
"status": true,
"message": "Graph Result",
"result": {
"graph-data": [
{
"name": "Graph A",
"value": 661041,
},
{
"name": "Graph B",
"value": 2277460,
},
{
"name": "Graph C",
"value": 1565178,
} ]
}
};
try this. Try to convert data from API into the given class before passing it.
I am trying to display both names of a person as a title in listtile flutter. This is the sample json file
var users = const [
{
"first_name": "melissa",
"last_name": "fleming",
"phone_number": "0740-304-475"
},
{
"first_name": "christoffer",
"last_name": "christiansen",
"phone_number": "05761325"
},
{
"first_name": "valtteri",
"last_name": "pulkkinen",
"phone_number": "041-829-79-61"
}
]
This is the flutter code
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
"List of Customers",
),
body: ListView.separated(
itemCount: users.length,
separatorBuilder: (context, index) => Divider(),
itemBuilder: (BuildContext context, int index) {
var user = users[index];
return ListTile(
title: Text(user['first_name']),
isThreeLine: true,
);
},
),
);
}
How can I pass both names to this part
title: Text(user['first_name']),
You can use for in loop and store the value in a String
for(var i in users){
String name = i['first_name'] + " "+ i['last_name'];
print(name);}
ListView.separated(
itemCount: users.length,
separatorBuilder: (context, index) => Divider(),
itemBuilder: (BuildContext context, int index) {
var user = users[index];
return ListTile(
title: Text(name),
isThreeLine: true,
);
},
),
there are two ways you can do it.
First Approach : if you want to show full name as title :
title : Text("$users[0]['first_name'] $users[0]['last_name']")
Second Approach : if you want to show first name and last name separately use subtitle :
ListTile(
leading: const Icon(Icons.flight_land),
title: const Text($users[0]['first_name']),
subtitle: Text($users[0]['last_name']),
onTap: () { /* react to the tile being tapped */ }
)
I'm new to programming world, I have do research from many source about this error but i've found nothing. I'm trying to build a ListView.builder in Flutter, where the itemBuilder is from my JSON response data like this:
{
"status": "success",
"data": {
"general": [
{
"id": 1,
"name": "Sumbangan Pembinaan Pendidikan",
"icon": "credit_card",
"type": "monthly",
"amount": 125000
},
{
"id": 2,
"name": "Uang Bangunan",
"icon": "credit_card",
"type": "yearly",
"amount": 1250000
}
],
"categorized": [
{
"name": "Bayar Buku",
"icon": "credit_card",
"childs": [
{
"id": 3,
"name": "Buku 1",
"icon": "credit_card",
"type": "monthly",
"amount": 324423
},
{
"id": 4,
"name": "Buku 2",
"icon": "credit_card",
"type": "monthly",
"amount": 16000
}
]
}
]
}
}
I need to get the 'name' of item to fetch with my ListView.builder, This is what I've come up with
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:sekolah_kita/components/constant.dart';
import 'package:http/http.dart' as http;
import 'package:sekolah_kita/components/storage.dart';
class DaftarTransaksi extends StatefulWidget {
#override
_DaftarTransaksiState createState() => _DaftarTransaksiState();
}
class _DaftarTransaksiState extends State<DaftarTransaksi> {
final SecureStorage secureStorage = SecureStorage();
List studentFeesData;
bool isLoading = true;
#override
void initState() {
secureStorage.readSecureData('student_token').then((value) {
getStudentFees(
value,
);
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: secondaryColor,
appBar: AppBar(
leading: IconButton(
onPressed: (){
Navigator.pop(context);
},
icon: Icon(
Icons.arrow_back
),
),
backgroundColor: primaryColor,
elevation: 0,
centerTitle: true,
title: Text(
'Transaksi',
style: TextStyle(
fontSize: screenWidth(context)*(1/25),
),
),
),
body: isLoading ? Center(
child: CircularProgressIndicator(
backgroundColor: primaryColor,
),
) : Center(
child: Container(
margin: EdgeInsets.symmetric(
vertical: screenHeight(context)*(1/30),
horizontal: screenWidth(context)*(1/20),
),
color: Colors.green.withOpacity(0.5),
child: ListView.builder(
itemCount: studentFeesData == 0 ? 0 : studentFeesData.length,
itemBuilder: (context, index){
return studentFeeButtonMenu(
context,
studentFeesData[index]['data']['general']['name'],
Icons.credit_card);
},
),
),
),
);
}
Future<String> getStudentFees(String token) async{
var uri = Uri.https('sekolahkita.zonaku.com', '/api/school-fee/bill');
http.Response response = await http.get(
uri,
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: "Bearer "+token,
},
);
var data = json.decode(response.body);
studentFeesData = List<dynamic>.from(
data.map<dynamic>(
(dynamic item) => item,
)
);
}
Widget studentFeeButtonMenu(BuildContext context, String text, IconData iconFee){
return Container(
width: double.infinity,
height: screenHeight(context)*(1/12),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: Container(
width: screenWidth(context)*(1/1.3),
height: double.infinity,
color: Colors.red,
child: Row(
children: [
Icon(
iconFee,
color: Color(0xff84923f),
),
SizedBox(
width: screenWidth(context)*(1/10),
),
Text(
text,
style: TextStyle(
color: Colors.black,
),
),
],
),
),
),
);
}
}
But I've always get an error to display what i want in ListView.builder. The runtime type of my JSON response is '_InternalLinkedHashMap<String, dynamic>', and I know I need to convert it to List, so it can be fitted with studentFeesData variable to display it in ListView.builder.
This is my error message:
Exception has occurred.
NoSuchMethodError (NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'map' with matching arguments.
Receiver: _LinkedHashMap len:2
Tried calling: map(Closure: (dynamic) => dynamic)
Found: map<K2, V2>((K, V) => MapEntry<K2, V2>) => Map<K2, V2>)
I hope anyone can help me with this.
You need to convert your json data to a model object for easier access.
I have converted your json data as follows:
StudentFeesModel
GeneralModel
CategorizedModel
Now, you can access & iterate over the list of GeneralModel & CategorizedModel to get the names of the children.
Here is the snippet:
import 'dart:convert';
void main() {
dynamic data = {
"status": "success",
"data": {
"general": [
{
"id": 1,
"name": "Sumbangan Pembinaan Pendidikan",
"icon": "credit_card",
"type": "monthly",
"amount": 125000
},
{
"id": 2,
"name": "Uang Bangunan",
"icon": "credit_card",
"type": "yearly",
"amount": 1250000
}
],
"categorized": [
{
"name": "Bayar Buku",
"icon": "credit_card",
"childs": [
{
"id": 3,
"name": "Buku 1",
"icon": "credit_card",
"type": "monthly",
"amount": 324423
},
{
"id": 4,
"name": "Buku 2",
"icon": "credit_card",
"type": "monthly",
"amount": 16000
}
]
}
]
}
};
// NOTE: You just need to pass data instead of data["data"] i.e,
// You should write the following:
// StudentFeesModel studentFeesData = StudentFeesModel.fromJson(data);
StudentFeesModel studentFeesData = StudentFeesModel.fromJson(data["data"]);
List generalNames = studentFeesData.general.map((generalModel) => generalModel.name).toList();
List categorizedNames = studentFeesData.categorized.map((categorizedModel) => categorizedModel.name).toList();
print("General names: " + generalNames.toString());
print("Categorized names: " + categorizedNames.toString());
// If you want categorized child names, then
// Iterate over all categorized objects & add all child names to a single list
List categorizedChildNames = [];
for(dynamic categorized in studentFeesData.categorized) {
categorizedChildNames.addAll(categorized.childs.map((childObject) => childObject.name).toList());
}
print("Categorized child names: " + categorizedChildNames.toString());
}
// **************************
// Model classes
// **************************
class StudentFeesModel {
StudentFeesModel({
this.general,
this.categorized,
});
final List<dynamic> general, categorized;
factory StudentFeesModel.fromJson(dynamic json) {
return StudentFeesModel(
general: GeneralModel.listOfGeneralModel(json["general"]),
categorized: CategorizedModel.listOfCategorizedModel(json["categorized"]),
);
}
dynamic toJson() => {
"general": general,
"categorized": categorized,
};
#override
String toString() {
return '${JsonEncoder.withIndent(' ').convert(this)}';
}
}
class GeneralModel {
GeneralModel({
this.id,
this.name,
this.icon,
this.type,
this.amount,
});
final int id, amount;
final String name, icon, type;
factory GeneralModel.fromJson(dynamic json) {
if (json == null) return null;
return GeneralModel(
id: json["id"],
name: json["name"],
icon: json["icon"],
type: json["type"],
amount: json["amount"],
);
}
static List<dynamic> listOfGeneralModel(dynamic list) {
if (list == null) return null;
dynamic generalModelList = [];
for (dynamic json in list) {
generalModelList.add(GeneralModel.fromJson(json));
}
return generalModelList;
}
dynamic toJson() => {
"id": id,
"name": name,
"icon": icon,
"type": type,
"amount": amount,
};
#override
String toString() {
return '${JsonEncoder.withIndent(' ').convert(this)}';
}
}
class CategorizedModel {
CategorizedModel({
this.name,
this.icon,
this.childs, // children would be more appropriate
});
final String name, icon;
final List<dynamic> childs; // children would be more appropriate
factory CategorizedModel.fromJson(dynamic json) {
return CategorizedModel(
name: json["name"],
icon: json["icon"],
childs: GeneralModel.listOfGeneralModel(json["childs"]), // children would be more appropriate
);
}
static List<dynamic> listOfCategorizedModel(List<dynamic> list) {
if (list == null) return null;
List categorizedModelList = [];
for (dynamic json in list) {
categorizedModelList.add(CategorizedModel.fromJson(json));
}
return categorizedModelList;
}
dynamic toJson() => {
"name": name,
"icon": icon,
"childs": childs,
};
#override
String toString() {
return '${JsonEncoder.withIndent(' ').convert(this)}';
}
}
this is my API response
var = ''' [
{
"entity_id": "86",
"building_name": "Burj Khalifa",
"location": "Al Ttay",
"image_field": "1595916594oad.jpeg"
},
{
"entity_id": "87",
"building_name": "Azmair",
"location": " Eyal Nasser ",
"image_field": "1596541099s.jpeg"
},
{
"entity_id": "88",
"building_name": "Bella Casa",
"location": "Hatta",
"image_field": "15965463423abe68a5bc11733effefeb91194_767x0.jpg"
}
]''';
I am making it as a string using
var decoded = response as List;
var buildgnames = decoded.map<String>((e) => e['building_name']).toList();
how to get "entity_id" with the when select building name in a list?
like when I choose "Burj Khalifa" in a drop-down I want to get the "id" of it
Here is a great guide on how json and serialization works in Flutter:
https://flutter.dev/docs/development/data-and-backend/json
Basically you create a model for your data structure:
class Entity {
int entityId;
String buildingName;
String location;
String imageField;
Entity({this.entityId, this.buildingName, this.location, this.imageField});
Entity.fromJson(Map<String, dynamic> json) :
entityId = json["entity_id"],
buildingName = json["building_name"],
location = json["location"],
imageField = json["imageField"];
}
When you have done that, you can deserialize your json like this using the dart:convert package:
var jsonMap = jsonDecode(jsonString);
var entity = Entity.fromJson(jsonMap);
After this you can put your entity as the data to select in the dropdown. And when you select "Burj Khalifa". You can simply check entity.id
DropdownButtonFormField(
hint: Text("Building"),
onChanged: ((val) {
setState((){
print(val. entity_id);
selectedBuilding = val;
});
}),
value: selectedBuilding ?? null,
items: buildingList.map<DropdownMenuItem>((BuildingModel value) {
return DropdownMenuItem(
value: value,
child: Text(value.building_name),
);
}).toList(),
decoration: InputDecoration(
icon: Icon(Icons.access_time)
),
);
You can get your selected building model :
onChanged: ((val) {
setState((){
print(val. entity_id);
selectedBuilding = val;
});
}),
you can use foreach for accessing each element of list like
decoded.forEach((element) {
var entity_id = element['entity_id'];
})
In your case when you select the drop down button you will get the index of item use that index and fetch it like this
var entity_id = decoded.elementAt(index)['entity_id'];
First of all you have to create model class.
class Building {
String id;
String buildingName;
String location;
String imageField;
Building({this.id, this.buildingName, this.location, this.imageField});
Building.fromJson(Map<String, dynamic> json) {
id = json['entity_id'];
buildingName = json['building_name'];
location = json['location'];
imageField = json['image_field'];
}
}
After that convert response to Building object.
Iterable mJson = json.decode(response.body);
List<Building> buildingList = mJson.map((model) => Building.fromJson(model)).toList();
Show building list name and return building id when click.
Expanded(
child: ListView.separated(
separatorBuilder: (context, index) => Divider(
color: Colors.grey,
),
itemCount: buildings?.length ?? 0,
itemBuilder: (BuildContext ctxt, int index) {
return InkWell(
onTap: () => _handleRowTap(buildings[index].id),
child: Padding(
padding: EdgeInsets.all(8),
child: Text(
"${buildings[index].buildingName}",
),
));
}));
And the latest.
_handleRowTap(String buildingId) {
//Handle click event here
}