Get and draw GoogleMap Marker from JSON file - google-maps

My simple application that get marker information from local JSON files and draws them.
It look like clear but I got a problem, it is just drawing the map, not show the marker.
I have consulted many guidelines and have applied but failed.
I sure added assets: - assets/data.json on pubspec.yaml
This is my main.dart code
class _MyHomePageState extends State<MyHomePage> {
Future _future;
List<Marker> allMarkers = [];
Future<String> loadJson() async =>
await rootBundle.loadString('assets/data.json');
GoogleMapController _controller;
#override
void initState() {
_future = loadJson();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(
children: <Widget>[
FutureBuilder(
future: _future,
builder: (context, snapshot) {
if (snapshot.hasData) {
for (var v in snapshot.data) {
allMarkers.add(Marker(
markerId: v['id'],
position: LatLng(v['x'], v['y']),
));
}
return Text(snapshot.data);
} else {
return CircularProgressIndicator();
}
}),
GoogleMap(
initialCameraPosition:
CameraPosition(target: LatLng(40.7128, -74.0060), zoom: 12.0),
markers: Set.from(allMarkers),
onMapCreated: mapCreated,
),
],
),
));
}
void mapCreated(controller) {
setState(() {
_controller = controller;
});
}
}
My data.json
[{
"rownum": 1,
"id": "E3E0D2C5-CB82-4AF3-8D5D-4CD323560F59",
"x": 40.7128,
"y": -74.0060,
}, {
"rownum": 2,
"id": "5FFB6736-7D1F-4B40-A397-32EB3128BC30",
"x": 41.7128,
"y": -71.0060,
}]

Related

How to add marker in the google map using json API in flutter?

I'm trying to add marker to my map based on the json API (EventData) by using http request. When I run my code the map does not show the marker. I think I am not accessing the list correctly. I want just to use these parameters: GPSPoint_lat , GPSPoint_lon and Address from EventData. can someone help me?
This is my json :
{
"Account": "",
"Account_desc": "",
"TimeZone": "GMT+00:00",
"DeviceList": [
{
"Device": "v19",
"Device_desc": "541266 DACIA NOIR",
"VehicleID": "",
"State": "62467",
"LastNotifyText": "",
"LastTimestamp": "1618683994",
"LastGPSTimestamp": 1618700203,
"Icon": "",
"DeviceCode": "tk12x",
"lastEngineHours": 4.5025,
"FuelLevel": 0.0,
"FuelTotal": "0.0 %",
"simPhoneNumber": "0607250761",
"EventData": [
{
"Device": "v19",
"Timestamp": 1618700203,
"Timestamp_date": "2021/04/17",
"Timestamp_time": "22:56:43",
"StatusCode": 62467,
"StatusCode_hex": "0xF403",
"StatusCode_desc": "Moteur OFF",
"GPSPoint": "35.74512,-5.85550",
"GPSPoint_lat": 35.74512,
"GPSPoint_lon": -5.85550,
"Speed_kph": 0.0,
"Speed": 0.0,
"Speed_units": "Km/H",
"Heading": 0.0,
"Heading_desc": "N",
"Altitude_meters": 0.0,
"Altitude": 0,
"Altitude_units": "meters",
"Odometer_km": 22438.364,
"Odometer": 22438.364,
"Odometer_units": "Distance en Kilomètre",
"Geozone": "",
"Geozone_index": 0,
"Address": "Tanger, 90045, Maroc",
"City": "Tanger",
"PostalCode": "90045",
"DigitalInputMask": 62467,
"DriverID": "",
"EngineHours": 4.50,
"acceleration": 0.00,
"brakeGForce": 0.00,
"EngineCoolantTemperature_C": 0.0,
"EngineCoolantTemperature": 32.0,
"EngineCoolantTemperature_units": "F",
"ThermoAverage_C": 0.0,
"ThermoAverage": 32.0,
"ThermoAverage_units": "F",
"EngineFuelUsed_Liter": 0.0,
"EngineFuelUsed": 0.0,
"EngineFuelUsed_units": "Litre",
"Index": 0
}
]
}
],
"consomFuelL": 0.0,
"consomFuelPr": "0.0 %",
"debug": "",
"maxspeed": 0.0,
"KM": 22129.80960258997,
"KMtotal": 22129.80960258997,
"minStop": 0,
"minOn": 0,
"minMarche": 0,
"Costfuel": 0.0
}
My code :
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Maps (title: 'Flutter Demo Home Page'),
);
}
}
class Maps extends StatefulWidget {
#override
_MapsPageState createState() => _MapsPageState();
}
class _MapsPageState extends State<Maps> {
String data;
var superheros_length;
String ValRet;
int index;
#override
void initState() {
// TODO: implement initState
super.initState();
// setCustomMarker();
getData();
}
Set<Marker> _markers = {};
//worked
void _onMapCreated(GoogleMapController controller) async{
final googleOffices = await getData();
setState(() {
for (final dnn in googleOffices.jsonDecode(data)['DeviceList']) {
_markers.clear();
_markers.add(
Marker(markerId: MarkerId(dnn.jsonDecode(data)['DeviceList']['Device']),
position: LatLng(35.77561, -5.80351),
// icon: mapMarker,
infoWindow: InfoWindow(
title: dnn.jsonDecode(data)['DeviceList']['Device'],
snippet: dnn.jsonDecode(data)['DeviceList'][index]['address']
)
)
);
}
});
}
getData() async {
const googleLocationsURL = 'myAPIPrivate';
// Retrieve the locations of Google offices
final response = await http.get(googleLocationsURL);
if (response.statusCode == 200) {
data =response.body;
superheros_length= jsonDecode(data)['DeviceList'];
print (superheros_length.length);
} else {
throw HttpException(
'Unexpected status code ${response.statusCode}:'
' ${response.reasonPhrase}',
uri: Uri.parse(googleLocationsURL));
}
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Maps Sample App'),
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.white),
onPressed: () => Navigator.of(context).pop(),
),
// backgroundColor: Colors.green[700],
),
body:
GoogleMap(
// mapType: _currentMapType,
onMapCreated: _onMapCreated,
markers: _markers,
initialCameraPosition: CameraPosition(
target: const LatLng(35.77561,-5.80351),
// target: _center,
// target: const LatLng(0,0),
zoom: 11.0,
),
// markers: _markers.values.toSet(),
),
),
);
}
}
error:
There are a few things that should probably be changed in the code.
var superheros_length; is misleading, I thought it was an integer at first, but based on your getData() function, it's a map. So, first off change it to:
List<Map<String, dynamic>> super_heros_length;
I would change the onMapCreated function to be something like this:
void _onMapCreated(GoogleMapController controller) async{
await getData();
_markers.clear();
for (final dnn in super_heros_length) {
setState(() {
_markers.add(
Marker(markerId: MarkerId(dnn['Device']),
position: LatLng(dnn["EventData"][0]["GPSPoint_lat"], dnn["EventData"][0]["GPSPoint_lon"]),
// icon: mapMarker,
infoWindow: InfoWindow(
title: dnn['Device'],
snippet: dnn["EventData"][0]['address']
)
)
);
});
}
}
To access the lat, based on your json, you have to use it like this:
["DeviceList"][0]["EventData"][0]["GPSPoint_lat"]
But since you are already accessing ["DeviceList"] and assigning it to superheroes_length, you don't have to repeat yourself, and use the code posted here, and update on what happens. Also post what errors you are recieving. You were also clearing your markees for every time you iterate in your for-loop, this way, if you had multiple markers, only the last marker will show, because every time you add a new marker, you were clearing everything before it, this is why I put it outside the loop.

i have a problem showing the json data in the drop-down list flutter

this is my first flutter JSON example, I tried to fetch data from the JSON link and display it on a drop-down list.
I am getting the response on the console but the drop-down list doesn't work
any help, please?......................................................................................................................................................................................................................................................................................................................
this is the body
ERROR
this is my code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
void initState() {
_getfamilyList();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
padding: EdgeInsets.only(left: 15, right: 15, top: 5),
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton<String>(
value: _myfamily,
iconSize: 30,
icon: (null),
style: TextStyle(
color: Colors.black54,
fontSize: 16,
),
hint: Text('Select family'),
onChanged: (String newValue) {
setState(() {
_myfamily = newValue;
print(_myfamily);
});
},
items: familysList?.map((item) {
return new DropdownMenuItem(
child: new Text(item['firsName']),
);
})?.toList() ??
[],
),
),
),
),
],
),
),
],
),
);
}
List familysList;
String _myfamily;
String familyInfoUrl =
'http://10.0.2.2:3000/genocheck/user/getmembrefamille/f1';
Future<String> _getfamilyList() async {
await http.get(familyInfoUrl).then((response) {
var data = json.decode(response.body);
print(data);
setState(() {
familysList = data['famille'];
});
});
}
}
as I see the problem is in your JSON response
famille is the first element ,
the list of data is the second element
however in your code familysList = data['famille'];
you are assuming that famille is a key and the list of data is the value and this is not correct
so answer is one of those
1 - make your asignment like familysList = data[0];
2- change your json to be {"famille" :[{"id":8654,"firstname":"some name"]"}
The error caused because although data's type is List that can access by 'int' index, you access like Map.
data['famille']
As your data body, data[0] is 'famille' and data[1] is data what you want.
data[1] is
[
{
"_id": "",
"firstName": "",
}
]
You can copy paste run full code below
Step 1: data[0] is String famille, data[1] is List you want
familysList = data[1];
Step 2: firsName is typo you need firstName
Step 3: DropdownMenuItem need value attribute
items: familysList?.map((item) {
return DropdownMenuItem<String>(
child: Text("${item["firstName"]}"),
value: item["firstName"],
);
})?.toList() ??
working demo
full code
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
void initState() {
_getfamilyList();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
padding: EdgeInsets.only(left: 15, right: 15, top: 5),
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton<String>(
value: _myfamily,
iconSize: 30,
icon: (null),
style: TextStyle(
color: Colors.black54,
fontSize: 16,
),
hint: Text('Select family'),
onChanged: (String Value) {
setState(() {
_myfamily = Value;
print("_myfamily $_myfamily");
});
},
items: familysList?.map((item) {
//print(item["firstName"]);
return DropdownMenuItem<String>(
child: Text("${item["firstName"]}"),
value: item["firstName"],
);
})?.toList() ??
[],
),
),
),
),
],
),
),
],
),
);
}
List familysList;
String _myfamily;
String familyInfoUrl =
'http://10.0.2.2:3000/genocheck/user/getmembrefamille/f1';
Future<String> _getfamilyList() async {
String jsonString = '''
[
"famille",
[
{
"_id" : "123",
"firstName":"abc"
},
{
"_id" : "456",
"firstName":"def"
}
]
]
''';
http.Response response = http.Response(jsonString, 200);
var data = json.decode(response.body);
print(data);
setState(() {
familysList = data[1];
});
/*await http.get(familyInfoUrl).then((response) {
var data = json.decode(response.body);
print(data);
setState(() {
familysList = data[1];
});
});*/
}
}
full code 2 for new question
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
class UserElement {
UserElement({
this.id,
this.firstName,
});
String id;
String firstName;
factory UserElement.fromJson(Map<String, dynamic> json) => UserElement(
id: json["_id"] == null ? null : json["_id"],
firstName: json["firstName"] == null ? null : json["firstName"],
);
Map<String, dynamic> toJson() => {
"_id": id == null ? null : id,
"firstName": firstName == null ? null : firstName,
};
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
void initState() {
_getfamilyList();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
padding: EdgeInsets.only(left: 15, right: 15, top: 5),
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton<UserElement>(
value: _myfamily,
iconSize: 30,
icon: (null),
style: TextStyle(
color: Colors.black54,
fontSize: 16,
),
hint: Text('Select family'),
onChanged: (UserElement Value) {
setState(() {
_myfamily = Value;
print("_myfamily ${_myfamily.firstName}");
});
},
items: familysList?.map((item) {
return DropdownMenuItem<UserElement>(
child: Text("${item.id} ${item.firstName}"),
value: item,
);
})?.toList() ??
[],
),
),
),
),
],
),
),
],
),
);
}
List<UserElement> familysList = [];
UserElement _myfamily;
String familyInfoUrl =
'http://10.0.2.2:3000/genocheck/user/getmembrefamille/f1';
Future<String> _getfamilyList() async {
String jsonString = '''
[
"famille",
[
{
"_id" : "123",
"firstName":"abc"
},
{
"_id" : "456",
"firstName":"abc"
}
]
]
''';
http.Response response = http.Response(jsonString, 200);
var data = json.decode(response.body);
//print(data);
setState(() {
List<dynamic> listData = data[1];
for (var i = 0; i < listData.length; i++) {
familysList.add(UserElement.fromJson(listData[i]));
}
});
/*await http.get(familyInfoUrl).then((response) {
var data = json.decode(response.body);
print(data);
setState(() {
familysList = data['famille'];
});
});*/
}
}

How do I search through data in flutter app

I am new to flutter and I was following a tutorial that shows how to search through data. I cannot recreate that using my own example. I would like to know how to search through data in a ListView from this json data.
{
"success": "true",
"data": [
{
"id": 1,
"name": "football"
},
{
"id": 2,
"name": "rugby"
},
{
"id": 3,
"name": "basketball"
},
{
"id": 4,
"name": "hockey"
},
{
"id": 5,
"name": "tennis"
},
{
"id": 6,
"name": "golf"
}
]
}
Displayed using this code
if (snapshot.hasData) {
return ListView.builder(
itemCount: sports.games.length,
itemBuilder: (context, index) {
if (sports.games.length > 0) {
final x = sports.games[index];
final y = sports.games[index].id.toString();
return ListTile(
title: Text(y),
subtitle: Text(x.name),
);
}
},
);
}
},
First your JSON file will return as a Map, according to this answer at
Unhandled Exception: InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>
for your problem, here is the solution. First you need create a model like this, can be place at separate file or can be place at same file too
class Sports {
int id;
String name;
Sports({
this.id,
this.name,
});
factory Sports.fromJson(Map<String, dynamic> json) {
return Sports(id: json['id'], name: json['name']);
}
}
than here it's the main.dart
import 'package:aberdeen/model.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyApp> {
TextEditingController controller = new TextEditingController();
List<Sports> array = [];
List<Sports> _filtered = [];
List<Sports> _null_filtered = [];
String jsonTest =
'{"success": "true","data": [{"id": 1,"name": "football"},{"id": 2,"name": "rugby"},{"id": 3,"name": "basketball"},{"id": 4,"name": "hockey"},{"id": 5,"name": "tennis"},{"id": 6,"name": "golf"}]}';
void initState() {
super.initState();
test();
}
void _alterfilter(String query) {
List<Sports> dummySearchList = [];
dummySearchList.addAll(_filtered);
if (query.isNotEmpty) {
List<Sports> dummyListData = [];
dummySearchList.forEach((item) {
if (item.name.contains(query)) { //if you want to search it order by id you can change item.name.contains to item.id.contains
dummyListData.add(item);
}
});
setState(() {
_filtered.clear();
_filtered.addAll(dummyListData); //dummyListData will place all the data that match at your search bar
});
return;
} else {
setState(() {
_filtered.clear();
_filtered.addAll(_null_filtered); //_null_filtered will place all the data if search bar was empty after enter a words
});
}
}
Future<Sports> test() async {
Map<String, dynamic> tagObjsJson = json.decode(jsonTest);
List<dynamic> data = tagObjsJson["data"];
setState(() {
for (Map Data in data) {
array.add(Sports.fromJson(Data));
}
_filtered.addAll(array);
_null_filtered.addAll(array);
for (int a = 0; a < _filtered.length; a++) {
print(_filtered[a].name);
}
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Container(
alignment: Alignment.center,
child: Container(
margin: const EdgeInsets.only(top: 50),
width: 300,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
border: Border.all(
width: 1,
color: Color.fromRGBO(11, 189, 180, 1),
style: BorderStyle.solid)),
child: TextField(
decoration: InputDecoration(
hintText: 'Search your data',
contentPadding: EdgeInsets.all(15),
border: InputBorder.none),
controller: controller,
onChanged: (value) {
_alterfilter(value);
},
),
),
),
],
),
Expanded(
child: Container(
margin: const EdgeInsets.all(20),
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: _filtered.length,
itemBuilder: (context, index) {
if (array.length > 0) {
final x = _filtered[index];
final y = _filtered[index].id.toString();
return ListTile(
title: Text(y),
subtitle: Text(x.name),
);
}
},
),
))
],
),
),
));
}
}
Sorry mate if my english was very bad but tell me if you got confused

Flutter - ListView.builder() not working after the JSON fetch

I am trying to load the JSON from a local variable in my class file and convert the JSON to a list of objects using PODO class but I don't know why the list isn't getting generated. I am so much frustrated. Please help me where I am doing wrong.
I have tried every possible way by manipulating the code, even the same code works for a different JSON format with its PODO class.
Thank you.
Flutter class source code:
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class Demo extends StatefulWidget {
#override
_Demo createState() => _Demo();
}
class _Demo extends State<Demo> {
final localJson = '''
[
{
"message": "Some message here 1"
},
{
"message": "Some message here 2"
},
{
"message": "Some message here 3"
}
]
''';
Widget getCommentItem({#required PodoClass item}) {
return Text(item.message);
}
Future<List<PodoClass>> fetchComments() async {
return compute(parseJson, localJson);
}
List<PodoClass> parseJson(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<PodoClass>((json) => PodoClass.fromJson(json)).toList();
}
Widget _bodyBuild({#required List<PodoClass> items}) {
return ListView.builder(
physics: BouncingScrollPhysics(),
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 20),
itemCount: items.length,
itemBuilder: (BuildContext ctxt, int index) {
return getCommentItem(item: items[index]);
});
}
Widget body() {
return FutureBuilder<List<PodoClass>>(
future: fetchComments(),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? _bodyBuild(items: snapshot.data)
: Center(child: Text('Loading..'));
},
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: false,
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Comments",
),
Text("Battle ID", style: TextStyle(fontSize: 12))
])),
body: body());
}
}
// podo class
class PodoClass {
String message;
PodoClass({this.message});
PodoClass.fromJson(Map<String, dynamic> json) {
message = json['message'];
}
}
you must move parseJson function outside the class
it should be top level function
https://api.flutter.dev/flutter/foundation/compute.html
The callback argument must be a top-level function, not a closure or
an instance or static method of a class.
The compute does not work in this case, simply call the function.
I've included a delay which may help you with testing.
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class Demo extends StatefulWidget {
#override
_Demo createState() => _Demo();
}
class _Demo extends State<Demo> {
final localJson = '''
[
{
"message": "Some message here 1"
},
{
"message": "Some message here 2"
},
{
"message": "Some message here 3"
}
]
''';
Widget getCommentItem({#required PodoClass item}) {
return Text(item.message);
}
Future<List<PodoClass>> fetchComments() async {
await Future.delayed(Duration(seconds: 5));
return parseJson(localJson);
}
List<PodoClass> parseJson(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<PodoClass>((json) => PodoClass.fromJson(json)).toList();
}
Widget _bodyBuild({#required List<PodoClass> items}) {
return ListView.builder(
physics: BouncingScrollPhysics(),
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 20),
itemCount: items.length,
itemBuilder: (BuildContext ctxt, int index) {
return getCommentItem(item: items[index]);
});
}
Widget body() {
return FutureBuilder<List<PodoClass>>(
future: fetchComments(),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? _bodyBuild(items: snapshot.data)
: Center(child: Text('Loading..'));
},
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: false,
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Comments",
),
Text("Battle ID", style: TextStyle(fontSize: 12))
])),
body: body());
}
}
// podo class
class PodoClass {
String message;
PodoClass({this.message});
PodoClass.fromJson(Map<String, dynamic> json) {
message = json['message'];
}
}

returning a widget based on the json result from POST method in flutter

my dashboard.dart look like this
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:abc/utils/connection_config.dart';
import 'package:abc/screens/loginpage.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/cupertino.dart';
class Dash extends StatefulWidget {
#override
DashState createState() => DashState();
}
class DashState extends State<Dash> {
Future reportList;
#override
void initState() {
super.initState();
reportList = getDashboardData();
}
getDashboardData() async {
var fromtime = 1567449000000;
var totime = 1567770486144;
var mtype = "internet";
http.Response response = await http.post(dashboardURL,
headers: {"Content-type": "application/json"},
body: json.encode({
"fromTime": fromtime,
"mtype": mtype,
"must": [
{"msg_status": "0"}
],
"toTime": totime
}));
switch (response.statusCode) {
case 200:
String dashboardResult = response.body;
var collection = json.decode(dashboardResult);
return collection;
break;
case 403:
case 401:
return null;
default:
return 1;
}
}
Widget getContents(BuildContext context, var data) { //here I want to return the widget for each entry in hits array
Widget _widget;
_widget = SingleChildScrollView(
child: SingleChildScrollView(
child: Container(
child: ,
),
),
);
return _widget;
}
//function that iterates over the list
getRefreshScaffold() {
return Center(
child: RaisedButton(
onPressed: () {
setState(() {
reportList = getDashboardData();
});
},
child: Text('Refresh, Network issues.'),
),
);
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: reportList,
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
case ConnectionState.active:
return Center(
child: CircularProgressIndicator(),
);
case ConnectionState.done:
var data = snapshot.data;
if (snapshot.hasData && !snapshot.hasError) {
return Container(
child: getContents(context, snapshot.data),
);
} else if (data == null) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text("Timeout! Log back in to continue"),
Padding(
padding: EdgeInsets.all(25.0),
),
RaisedButton(
onPressed: () {
setState(() {
token = null;
});
Navigator.of(context).pushReplacement(
CupertinoPageRoute(
builder: (BuildContext context) => LoginPage()),
);
},
child: Text('Login Again!'),
),
],
),
);
} else {
getRefreshScaffold();
}
}
},
);
}
}
Here I am hitting an api that gives the json there i need to loop over the following ,
{
..... some other data
"hitsArray": [
{
"tt": 1567566438144,
"status": "0",
"count": 2257056,
"status_count": 2257053
},
{
"tt": 1567566438144,
"status": "1",
"count": 2257056,
"status_count": 3
}
],
...some other data
}
what iam trying to do is to loop over the hitsarray in the json result and to display each entry in a widget.
but i am not getting how to loop over the json data and assign an widget to display it, I tried my best but not able to get it.
paste your json string to https://app.quicktype.io/ and you can get correct parsing logic and you can display with ListView
you can modify delay during to simulate network delay.
await new Future.delayed(new Duration(seconds: 10));
if your json string look like this
[
{
"tt": 1567566438144,
"status": "0",
"count": 2257056,
"status_count": 2257053
}
,
{
"tt": 1567566438144,
"status": "1",
"count": 2257056,
"status_count": 3
}
]
logic from quicktype
// To parse this JSON data, do
//
// final hitsArray = hitsArrayFromJson(jsonString);
import 'dart:convert';
List<HitsArray> hitsArrayFromJson(String str) => List<HitsArray>.from(json.decode(str).map((x) => HitsArray.fromJson(x)));
String hitsArrayToJson(List<HitsArray> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class HitsArray {
int tt;
String status;
int count;
int statusCount;
HitsArray({
this.tt,
this.status,
this.count,
this.statusCount,
});
factory HitsArray.fromJson(Map<String, dynamic> json) => HitsArray(
tt: json["tt"],
status: json["status"],
count: json["count"],
statusCount: json["status_count"],
);
Map<String, dynamic> toJson() => {
"tt": tt,
"status": status,
"count": count,
"status_count": statusCount,
};
}
demo full code display with FutureBuilder and ListView
import 'dart:async';
import 'package:flutter/material.dart';
// To parse this JSON data, do
//
// final hitsArray = hitsArrayFromJson(jsonString);
import 'dart:convert';
List<HitsArray> hitsArrayFromJson(String str) => List<HitsArray>.from(json.decode(str).map((x) => HitsArray.fromJson(x)));
String hitsArrayToJson(List<HitsArray> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class HitsArray {
int tt;
String status;
int count;
int statusCount;
HitsArray({
this.tt,
this.status,
this.count,
this.statusCount,
});
factory HitsArray.fromJson(Map<String, dynamic> json) => HitsArray(
tt: json["tt"],
status: json["status"],
count: json["count"],
statusCount: json["status_count"],
);
Map<String, dynamic> toJson() => {
"tt": tt,
"status": status,
"count": count,
"status_count": statusCount,
};
}
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
var futureBuilder = new FutureBuilder(
future: _getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return new Text('loading...');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return createListView(context, snapshot);
}
},
);
return new Scaffold(
appBar: new AppBar(
title: new Text("Home Page"),
),
body: futureBuilder,
);
}
Future<List<HitsArray>> _getData() async {
String jsonString = ' [ { "tt": 1567566438144, "status": "0", "count": 2257056, "status_count": 2257053 } , { "tt": 1567566438144, "status": "1", "count": 2257056, "status_count": 3 } ]';
var values = hitsArrayFromJson(jsonString);
//throw new Exception("Danger Will Robinson!!!");
await new Future.delayed(new Duration(seconds: 1));
return values;
}
Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
List<HitsArray> values = snapshot.data;
return new ListView.builder(
itemCount: values.length,
itemBuilder: (BuildContext context, int index) {
return new Column(
children: <Widget>[
new ListTile(
title: new Text(' count ${values[index].count.toString()}'),
subtitle: new Text('status count ${values[index].statusCount.toString()}'),
),
new Divider(height: 2.0,),
],
);
},
);
}
}