Parsing complex json flutter - json

I am trying to parse a complex json file into my application
I am getting an error Exception: type 'String' is not a subtype of type 'int' in type cast. I don't understand where this is happening and how to fix it
Code
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<Character>> fetchCharacters(http.Client client) async {
final response =
await client.get('http://swapi.dev/api/people/');
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parseCharacter, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Character> parseCharacter(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Character>((json) => Character.fromJson(json)).toList();
}
class Character {
final String name;
final int height;
final int mass;
final String hairColor;
final String skinColor;
Character({this.name, this.height, this.mass, this.hairColor, this.skinColor});
factory Character.fromJson(Map<String, dynamic> json) {
return Character(
name: json['name'] as String,
height: json['height'] as int,
mass: json['mass'] as int,
hairColor: json['hair_color'] as String,
skinColor: json['skin_color'] as String,
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final appTitle = 'Isolate Demo';
return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: FutureBuilder<List<Character>>(
future: fetchCharacters(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? PhotosList(character: snapshot.data)
: Center(child: CircularProgressIndicator());
},
),
);
}
}
class PhotosList extends StatelessWidget {
final List<Character> character;
PhotosList({Key key, this.character}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: character.length,
itemBuilder: (context, index) {
return Card(
elevation: 5,
margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
child: Container(
padding: EdgeInsets.all(15),
child: ListTile(
title: Text(
character[index].name,
style: TextStyle(fontSize: 18, color: Colors.black),
),
onTap: () {},
),
),
);
},
);
}
}
json file
"count": 82,
"next": "http://swapi.dev/api/people/?page=2",
"previous": null,
"results": [
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "http://swapi.dev/api/planets/1/",
"films": [
"http://swapi.dev/api/films/1/",
"http://swapi.dev/api/films/2/",
"http://swapi.dev/api/films/3/",
"http://swapi.dev/api/films/6/"
],
"species": [],
"vehicles": [
"http://swapi.dev/api/vehicles/14/",
"http://swapi.dev/api/vehicles/30/"
],
"starships": [
"http://swapi.dev/api/starships/12/",
"http://swapi.dev/api/starships/22/"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "http://swapi.dev/api/people/1/"
}
]
} ```

just remove as int that you added In your Constructor and use parseInt( json['mass'] ) and parseInt( json['height'] )
parseInt() is a function in dart to convert number string in type int to integer number can use in calculations and like that
check this also : https://dev.to/wangonya/how-you-turn-a-string-into-a-number-or-vice-versa-with-dart-392h

Related

Show nested JSON from API in single Page with multiple lists

Im new in Flutter and i'm struggeling with a nested JSON from API which data i want to show in one single page.
I get this JSON from a URL and decode it in a class, which is working fine:
{
"service1": [
{
"firstname": "Peter",
"lastname": "Smith"
},
{
"firstname": "Paul",
"lastname": "Johnson"
}
],
"service2": [
{
"firstname": "Mary",
"lastname": "Williams"
},
{
"firstname": "Guy",
"lastname": "Brown"
}
]
}
Classes:
/*------------------------------
staff.dart
------------------------------*/
import 'dart:convert';
class Staff {
String? service;
String? firstname;
String? lastname;
Staff({this.service, this.firstname, this.lastname});
factory Staff.fromMap(Map<String, dynamic> data) => Staff(
service: data['service'] as String?,
firstname: data['firstname'] as String?,
lastname: data['lastname'] as String?,
);
Map<String, dynamic> toMap() => {
'service': '',
'firstname': firstname,
'lastname': lastname,
};
/// Parses the string and returns the resulting Json object.
factory Staff.fromJson(String data) {
return Staff.fromMap(json.decode(data) as Map<String, dynamic>);
}
/// Converts [Staff] to a JSON string.
String toJson() => json.encode(toMap());
}
/*------------------------------
servicedesk.dart
------------------------------*/
import 'dart:convert';
import 'staff.dart';
class ServiceDesk {
List<Staff>? service1;
List<Staff>? service2;
ServiceDesk({
this.service1,
this.service2,
});
factory ServiceDesk.fromMap(Map<String, dynamic> data) => ServiceDesk(
service1: (data['service1'] as List<dynamic>?)
?.map((e) => Staff.fromMap(e as Map<String, dynamic>))
.toList(),
service2: (data['service2'] as List<dynamic>?)
?.map((e) => Staff.fromMap(e as Map<String, dynamic>))
.toList(),
);
Map<String, dynamic> toMap() => {
'service1': service1?.map((e) => e.toMap()).toList(),
'service2': service2?.map((e) => e.toMap()).toList(),
};
/// Parses the string and returns the resulting Json object as [ServiceDesk].
factory ServiceDesk.fromJson(String data) {
var object = ServiceDesk.fromMap(json.decode(data) as Map<String, dynamic>);
object.b1!.insert(0, Staff(service: 'Title for Service1'));
object.b2!.insert(0, Staff(service: 'Title for Service2'));
return object;
}
/// Converts to a JSON string.
String toJson() => json.encode(toMap());
}
That's the code i have (Pseudocode between):
// PSEUDOCODE!!
Widget ListWithService(List<Staff>? entry) {
return ListView.builder(
itemCount: entry!.length,
padding: const EdgeInsets.all(2.0),
itemBuilder: (context, position) {
final item = entry[position];
if (item.service != null) {
return ListTile(
title: Text(
'${item.service}',
style: Theme.of(context).textTheme.headline5,
),
);
} else {
return ListTile(
title: Text(
'${item.firstname} ${item.lastname}',
style: Theme.of(context).textTheme.bodyText1,
),
);
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Service Desk'),
),
body: FutureBuilder<sdclass.ServiceDesk>(
future: getData(),
builder: (context, snapshot) {
if (snapshot.hasData == true) {
return [
ListWithService(snapshot.data.service1),
ListWithSercice(snapshot.data.service1);
] // PSEUDOCODE!!
} else if (snapshot.hasError) {
return const Icon(
Icons.error_outline,
color: Colors.red,
size: 60,
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
}
),
);
}
What i would have at the end should look like this on the full page:
Title for Service1 (Headline)
Peter Smith
Paul Johnson
Title for Service2 (Headline)
Mary Williams
Guy Brown
Could someone help me with the code to get it work?
Update Code
Thanks for your updated example. I tested it in my code. First, everything looks fine. But wenn i switch to the screen with the json, i get a error:
Expected a value of type 'FutureOr<Map<String, List<Map<String, String>>>>', but got one of type '_JsonMap'
import 'dart:convert';
import 'dart:core';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class ServiceDesk extends StatelessWidget {
const ServiceDesk({Key? key}) : super(key: key);
Future<Map<String, List<Map<String, String>>>> getData() async {
String link = "https://url-to-json-file.json";
final res = await http
.get(Uri.parse(link), headers: {"Accept": "application/json"});
if (res.statusCode == 200) {
var utf8decoded = utf8.decode(res.body.toString().codeUnits);
var decoded = json.decode(utf8decoded);
return decoded;
} else {
throw Exception('Failed to load JSON');
}
}
Widget listViewWidget(
Iterable<MapEntry<String, List<Map<String, String>>>> entries) {
return ListView.builder(
itemCount: entries.length,
padding: const EdgeInsets.all(2.0),
itemBuilder: (context, index) {
final entry = entries.elementAt(index);
final key = entry.key;
final values = entry.value;
return Column(
children: [
ListTile(
title: Text(
'Title for $key',
style: Theme.of(context).textTheme.headline5,
),
),
for (var person in values)
ListTile(
title: Text(
'${person["firstname"]} ${person["lastname"]}',
style: Theme.of(context).textTheme.bodyText1,
),
),
],
);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Service Desk'),
),
body: FutureBuilder(
future: getData(),
builder: (_,
AsyncSnapshot<Map<String, List<Map<String, String>>>> snapshot) {
if (snapshot.hasData == true) {
final entries = snapshot.data?.entries ?? {};
return listViewWidget(entries);
} else if (snapshot.hasError) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Icon(
Icons.error_outline,
color: Colors.red,
size: 60,
),
Text("Fehler: ${snapshot.error}"),
],
));
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
}),
);
}
}
In the Dart language, you can use for loop in the list, it makes it easier to work with Flutter UI.
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const RootView(),
);
}
}
class RootView extends StatelessWidget {
const RootView({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextButton(
child: const Text('GO TO SAFF SERVICE'),
onPressed: () {
Navigator.push(context, Home.route());
},
),
),
);
}
}
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
static Route route() {
return CupertinoPageRoute(builder: (_) => const Home());
}
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
late Future<StaffService> staffService;
#override
void initState() {
staffService = getStaffService();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Services')),
body: Center(
child: FutureBuilder<StaffService>(
future: staffService,
builder: (_, snapshot) {
if (snapshot.hasData) {
final saff = snapshot.data!;
return ListView(
children: [
if (saff.service1.isNotEmpty)
StaffServiceTile(
title: Text(
'Title for Service 1',
style: Theme.of(context).textTheme.headline5,
),
services: saff.service1,
),
if (saff.service2.isNotEmpty)
StaffServiceTile(
title: Text(
'Title for Service 2',
style: Theme.of(context).textTheme.headline5,
),
services: saff.service2,
),
],
);
} else if (snapshot.hasError) {
return const Text('Error on loaad data. Try again later.');
} else {
return const CircularProgressIndicator();
}
},
),
),
);
}
}
class StaffServiceTile extends StatelessWidget {
const StaffServiceTile({
Key? key,
required this.title,
required this.services,
}) : super(key: key);
final Widget title;
final List<Service> services;
#override
Widget build(BuildContext context) {
return Column(
children: [
ListTile(title: title),
for (var person in services)
ListTile(
title: Text(
'${person.firstname} ${person.lastname}',
),
),
],
);
}
}
class StaffService {
StaffService({this.service1 = const [], this.service2 = const []});
List<Service> service1, service2;
factory StaffService.fromJson(String str) {
return StaffService.fromMap(json.decode(str));
}
String toJson() => json.encode(toMap());
factory StaffService.fromMap(Map<String, dynamic> json) => StaffService(
service1: List<Service>.from(json["service1"].map((x) => Service.fromMap(x))),
service2: List<Service>.from(json["service2"].map((x) => Service.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"service1": List<dynamic>.from(service1.map((x) => x.toMap())),
"service2": List<dynamic>.from(service2.map((x) => x.toMap())),
};
}
class Service {
Service({this.firstname, this.lastname});
String? firstname, lastname;
factory Service.fromJson(String str) => Service.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Service.fromMap(Map<String, dynamic> json) => Service(
firstname: json["firstname"],
lastname: json["lastname"],
);
Map<String, dynamic> toMap() => {
"firstname": firstname,
"lastname": lastname,
};
}
Future<StaffService> getStaffService() async {
await Future.delayed(const Duration(seconds: 2));
return StaffService.fromMap(data); // <- use fromJson if you load data from the JSON.
}
final data = <String, List<Map<String, String>>>{
"service1": [
{"firstname": "Peter", "lastname": "Smith"},
{"firstname": "Paul", "lastname": "Johnson"}
],
"service2": [
{"firstname": "Mary", "lastname": "Williams"},
{"firstname": "Guy", "lastname": "Brown"}
]
};
Copy and paste in the DartPad to test it.

how to get complex json data in future builder dart

{
"count": 6,
"next": null,
"previous": null,
"results": [
{
"id": 6,
"title": "Java6",
"description": "Java Basic",
"category": {
"id": 1,
"name": "Math"
},
"sub_category": {
"id": 4,
"name": "Test"
},
"tag": "string",
"video": {
"id": 6,
"duration": 10,
"thumbnail": "https://ibb.co/MZkfS7Q",
"link": "https://youtu.be/RgMeVbPbn-Q",
"views": 0
},
"quiz": {
"mcq": [
{
"id": 6,
"question": "q",
"option1": "b",
"option2": "c",
"option3": "d",
"option4": "e",
"answer": 1,
"appears_at": 0
}
]
},
"avg_rating": 1,
"total_number_of_rating": 1
},]}
how can I show this JSON data in future builder in dart
I have tried this way
Future<dynamic> geteducators() async {
String serviceurl = "https://api.spiro.study/latest-videos";
var response = await http.get(serviceurl);
final jsonrespose = json.decode(response.body);
print('title: ${jsonrespose}');
Videos latestVideo = Videos.fromJson(jsonrespose);
return latestVideo.results;
}
#override
void initState() {
super.initState();
_futureeducators = geteducators();
}
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
final response =
await http.get(Uri.parse('https://dog.ceo/api/breeds/image/random'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class Album {
//final int userId;
final String message;
final String status;
// final String region;
// final String country;
// final String title;
Album({
//required this.userId,
required this.message,
required this.status,
// required this.country,
// required this.region,
//required this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
// userId: json['userId'],
message: json['message'],
status: json['status'],
// country: json['country'],
// region: json['region'],
//title: json['total'],
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
#override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(snapshot.data!.status),
Image(image: NetworkImage(snapshot.data!.message))
],
); //Text(snapshot.data!.ip);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
),
),
);
}
}
//in this way you can get json data and show it in grid or list view.
How to use nested future builder for complex json i mean I'm getting name.from same.json in array and other hand I'm getting values from some json but diffrent aaray and array name is similer to uppe

Flutter: JSON data , list under list

I have JSON data file that looks like this, as you can see the email is a list itself:
[
{
"index": 0,
"about": "text text text",
"email": [
"kjdkffsk#skfjsd.com",
"kjdkffsk#skfjsd.com",
],
"name": "sample name",
"picture": "https://kdjfksfjsdklfs.com"
},
{
"index": 1,
"about": "text text text",
"email": [
"kjdkffsk#skfjsd.com",
"kjdkffsk#skfjsd.com",
],
"name": "sample name ",
"picture": "https://kdjfksfjsdklfs.com"
},
{
"index": 2,
"about": "text text text",
"email": [
"kjdkffsk#skfjsd.com",
"kjdkffsk#skfjsd.com",
],
"name": "sample name",
"picture": "https://kdjfksfjsdklfs.com"
}
]
My code is the following, which is basically a listview builder that gets data from the above JSON. Now when the list is clicked it navigate to the next page where I need to show details of this user.
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
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(title: 'Users'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
Future _data;
class _MyHomePageState extends State<MyHomePage> {
Future<List<User>> _getUsers() async {
var data =
await DefaultAssetBundle.of(context).loadString("assets/test.json");
var jsonData = json.decode(data);
List<User> users = [];
for (var u in jsonData) {
User user =
User(u["index"], u["about"], u["name"], u["email"], u["picture"]);
users.add(user);
}
print(users.length);
return users;
}
#override
void initState() {
super.initState();
_data = _getUsers();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: Container(
child: FutureBuilder(
future: _data,
builder: (BuildContext context, AsyncSnapshot snapshot) {
print(snapshot.data);
if (snapshot.data == null) {
return Container(child: Center(child: Text("Loading...")));
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: CircleAvatar(
backgroundImage:
NetworkImage(snapshot.data[index].picture),
),
title: Text(snapshot.data[index].name),
// subtitle: Text(snapshot.data[index].email),
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) =>
DetailPage(snapshot.data[index])));
},
);
},
);
}
},
),
),
);
}
}
class DetailPage extends StatelessWidget {
final User user;
DetailPage(this.user);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(user.name),
),
body: Container(
child: Text(user.about),
),
);
}
}
class User {
final int index;
final String about;
final String name;
final String email;
final String picture;
User(this.index, this.about, this.name, this.email, this.picture);
}
I wanted to create Listview Builder in the second page for name and the email so that all the emails listed under the name.
can someone help I am not able to generate the second page list especially the email list.
Just check out this example and let me know if it works for you:
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:json_parsing_example/models.dart';
// To parse this JSON data, do
//
// final user = userFromJson(jsonString);
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(title: 'Users'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
Future _data;
class _MyHomePageState extends State<MyHomePage> {
Future<List<User>> _getUsers() async {
var data =
await DefaultAssetBundle.of(context).loadString("json/parse.json");
return userFromJson(data);
}
#override
void initState() {
super.initState();
_data = _getUsers();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: Container(
child: FutureBuilder<List<User>>(
future: _data,
builder: (BuildContext context, AsyncSnapshot snapshot) {
print(snapshot.data);
if (snapshot.data == null) {
return Container(child: Center(child: Text("Loading...")));
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: CircleAvatar(
backgroundImage:
NetworkImage(snapshot.data[index].picture),
),
title: Text(snapshot.data[index].name),
// subtitle: Text(snapshot.data[index].email),
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) =>
DetailPage(snapshot.data[index])));
},
);
},
);
}
},
),
),
);
}
}
class DetailPage extends StatefulWidget {
final User user;
DetailPage(this.user);
#override
_DetailPageState createState() => _DetailPageState();
}
class _DetailPageState extends State<DetailPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.user.name),
),
body: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
widget.user.name,
style: TextStyle(fontSize: 20),
),
),
ListView.builder(
shrinkWrap: true,
itemCount: widget.user.email.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(widget.user.email[index]),
));
},
),
],
),
),
);
}
}
Your model class :
// To parse this JSON data, do
//
// final user = userFromJson(jsonString);
import 'dart:convert';
List<User> userFromJson(String str) => List<User>.from(json.decode(str).map((x) => User.fromJson(x)));
String userToJson(List<User> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class User {
User({
this.index,
this.about,
this.email,
this.name,
this.picture,
});
int index;
String about;
List<String> email;
String name;
String picture;
factory User.fromJson(Map<String, dynamic> json) => User(
index: json["index"],
about: json["about"],
email: List<String>.from(json["email"].map((x) => x)),
name: json["name"],
picture: json["picture"],
);
Map<String, dynamic> toJson() => {
"index": index,
"about": about,
"email": List<dynamic>.from(email.map((x) => x)),
"name": name,
"picture": picture,
};
}
First of all:
You can use either
moor/moor_flutter moor flutter_moor
OR
built_value built_value
To map the json String and generate fromJson/toJson functions.
Example using moor:
First, create a moor database (if you have any question I am glad to answer).
Second, this would be the class you should use.
import 'dart:convert';
import 'package:db/moordb/database.dart';
import 'package:json_annotation/json_annotation.dart' as json;
import 'package:moor/moor.dart';
part 'user.g.dart';
#DataClassName("User")
class Users extends Table {
IntColumn get id => integer().nullable().autoIncrement()();
#JsonKey("index")
IntColumn get index => text().nullable()();
#JsonKey("about")
TextColumn get about => text().nullable()();
#JsonKey("email")
TextColumn get emails => text().map(const EmailConverter()).nullable()();
#JsonKey("name")
TextColumn get name => text().nullable()();
#JsonKey("picture")
TextColumn get picture => text().nullable()();
#override
Set<Column> get primaryKey => {id};
}
class EmailConverter extends TypeConverter<List<String>, String> {
const EmailConverter ();
#override
List<String> mapToDart(String fromDb) {
if (fromDb == null) {
return null;
}
List _emails = List<String>();
(jsonDecode(fromDb)).forEach((value) {
_emails.add(value);
});
return _emails;
}
#override
String mapToSql(List<dynamic> value) {
if (value == null) {
return null;
}
return jsonEncode(value);
}
}
Second:
It is preferred that you send the User object through:
Navigator arguments Navigation
or
An Inherited Widget Inherited Widget
In your case you are passing the object to the widget directly.
In conclusion, it is obvious that the String field email in your User object is not being populated by the decoded data which contains the emails in a List. (since you are using the Class User).
Note: lose the new keyword since it is no longer required in Dart 2

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,),
],
);
},
);
}
}