How to display in widget the complex JSON using flutter? - json

My problem is i don't know how to display the Object inside the Object of JSON.
But i already display the Outer Object like name, usermae etc. And i want to display the object inside the Address and Geo. Im new to JSON and flutter please guide me
i read this but i dont know what i need here
the code is from here
JSON OUTPUT json is from here
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
]
MODEL
i generate my model in here
import 'dart:convert';
List<UserModel> userModelFromJson(String str) =>
List<UserModel>.from(json.decode(str).map((x) => UserModel.fromJson(x)));
String userModelToJson(List<UserModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class UserModel {
int id;
String name;
String username;
String email;
Address address;
String phone;
String website;
Company company;
UserModel({
this.id,
this.name,
this.username,
this.email,
this.address,
this.phone,
this.website,
this.company,
});
factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(
id: json["id"],
name: json["name"],
username: json["username"],
email: json["email"],
address: Address.fromJson(json["address"]),
phone: json["phone"],
website: json["website"],
company: Company.fromJson(json["company"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"username": username,
"email": email,
"address": address.toJson(),
"phone": phone,
"website": website,
"company": company.toJson(),
};
}
class Address {
String street;
String suite;
String city;
String zipcode;
Geo geo;
Address({
this.street,
this.suite,
this.city,
this.zipcode,
this.geo,
});
factory Address.fromJson(Map<String, dynamic> json) => Address(
street: json["street"],
suite: json["suite"],
city: json["city"],
zipcode: json["zipcode"],
geo: Geo.fromJson(json["geo"]),
);
Map<String, dynamic> toJson() => {
"street": street,
"suite": suite,
"city": city,
"zipcode": zipcode,
"geo": geo.toJson(),
};
}
class Geo {
String lat;
String lng;
Geo({
this.lat,
this.lng,
});
factory Geo.fromJson(Map<String, dynamic> json) => Geo(
lat: json["lat"],
lng: json["lng"],
);
Map<String, dynamic> toJson() => {
"lat": lat,
"lng": lng,
};
}
class Company {
String name;
String catchPhrase;
String bs;
Company({
this.name,
this.catchPhrase,
this.bs,
});
factory Company.fromJson(Map<String, dynamic> json) => Company(
name: json["name"],
catchPhrase: json["catchPhrase"],
bs: json["bs"],
);
Map<String, dynamic> toJson() => {
"name": name,
"catchPhrase": catchPhrase,
"bs": bs,
};
}
Services.dart
class Services {
static const String url = 'https://jsonplaceholder.typicode.com/users';
static Future<List<UserModel>> getUsers() async {
try {
final response = await http.get(url);
if (200 == response.statusCode) {
final List<UserModel> users = userModelFromJson(response.body);
return users;
} else {
return List<UserModel>();
}
} catch (e) {
return List<UserModel>();
}
}
}
HomeView.dart
class _HomeViewState extends State<HomeView> {
List<UserModel> _users;
bool _loading;
#override
void initState() {
super.initState();
_loading = true;
Services.getUsers().then((users) {
setState(() {
_users = users;
_loading = false;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_loading ? 'Loading...' : 'Users'),
),
body: Container(
color: Colors.white,
child: ListView.builder(
itemCount: _users == null ? 0 : _users.length,
itemBuilder: (context, index) {
UserModel user = _users[index];
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
ListTile(
title: Text(user.name),
subtitle: Text(user.email),
trailing: Text(user.phone),
),
],
);
},
),
),
);
}
}
Thank you for your kindness

The model that you create is correct, you have (Good habit) only to check the objects inside your model before you parse them
UserModel.fromJson(Map<String, dynamic> json) {
// ...
address =
json['address'] != null ? new Address.fromJson(json['address']) : null;
company =
json['company'] != null ? new Company.fromJson(json['company']) : null;
// ...
}
On your service class use the fetch way that is set on flutter documentation to simplify your code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<UserModel>> fetchUsers(http.Client client) async {
final response =
await client.get('https://jsonplaceholder.typicode.com/users');
return parseUsers(response.body);
}
List<UserModel> parseUsers(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<UserModel>((json) => UserModel.fromJson(json)).toList();
}
and once you get the data from json you can access to every object based on the hierarchy inside the json, in your case the stateful widget would look like, where i replace the name and the phone with latitude inside the geo and city inside the address
class _HomeViewState extends State<HomeView> {
List<UserModel> _users;
bool _loading;
#override
void initState() {
super.initState();
_loading = true;
fetchUsers(http.Client()).then((users) {
setState(() {
_users = users;
_loading = false;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_loading ? 'Loading...' : 'Users'),
),
body: Container(
color: Colors.white,
child: ListView.builder(
itemCount: _users == null ? 0 : _users.length,
itemBuilder: (context, index) {
UserModel user = _users[index];
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
ListTile(
title: Text(user.name),
subtitle: Text(user.address.geo.lat),
trailing: Text(user.address.city),
),
],
);
},
),
),
);
}
}
I hope this help

You can copy paste run full code below
You can directly assign attribute
code snippet
title: Text('${user.name} ${user.address.city} ${user.address.geo.lat}'),
working demo
full code
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
List<UserModel> userModelFromJson(String str) =>
List<UserModel>.from(json.decode(str).map((x) => UserModel.fromJson(x)));
String userModelToJson(List<UserModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class UserModel {
int id;
String name;
String username;
String email;
Address address;
String phone;
String website;
Company company;
UserModel({
this.id,
this.name,
this.username,
this.email,
this.address,
this.phone,
this.website,
this.company,
});
factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(
id: json["id"],
name: json["name"],
username: json["username"],
email: json["email"],
address: Address.fromJson(json["address"]),
phone: json["phone"],
website: json["website"],
company: Company.fromJson(json["company"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"username": username,
"email": email,
"address": address.toJson(),
"phone": phone,
"website": website,
"company": company.toJson(),
};
}
class Address {
String street;
String suite;
String city;
String zipcode;
Geo geo;
Address({
this.street,
this.suite,
this.city,
this.zipcode,
this.geo,
});
factory Address.fromJson(Map<String, dynamic> json) => Address(
street: json["street"],
suite: json["suite"],
city: json["city"],
zipcode: json["zipcode"],
geo: Geo.fromJson(json["geo"]),
);
Map<String, dynamic> toJson() => {
"street": street,
"suite": suite,
"city": city,
"zipcode": zipcode,
"geo": geo.toJson(),
};
}
class Geo {
String lat;
String lng;
Geo({
this.lat,
this.lng,
});
factory Geo.fromJson(Map<String, dynamic> json) => Geo(
lat: json["lat"],
lng: json["lng"],
);
Map<String, dynamic> toJson() => {
"lat": lat,
"lng": lng,
};
}
class Company {
String name;
String catchPhrase;
String bs;
Company({
this.name,
this.catchPhrase,
this.bs,
});
factory Company.fromJson(Map<String, dynamic> json) => Company(
name: json["name"],
catchPhrase: json["catchPhrase"],
bs: json["bs"],
);
Map<String, dynamic> toJson() => {
"name": name,
"catchPhrase": catchPhrase,
"bs": bs,
};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomeView(title: 'Flutter Demo Home Page'),
);
}
}
class Services {
static const String url = 'https://jsonplaceholder.typicode.com/users';
static Future<List<UserModel>> getUsers() async {
try {
final response = await http.get(url);
if (200 == response.statusCode) {
final List<UserModel> users = userModelFromJson(response.body);
return users;
} else {
return List<UserModel>();
}
} catch (e) {
return List<UserModel>();
}
}
}
class HomeView extends StatefulWidget {
HomeView({Key key, this.title}) : super(key: key);
final String title;
#override
_HomeViewState createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
List<UserModel> _users;
bool _loading;
#override
void initState() {
super.initState();
_loading = true;
Services.getUsers().then((users) {
setState(() {
_users = users;
_loading = false;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_loading ? 'Loading...' : 'Users'),
),
body: Container(
color: Colors.white,
child: ListView.builder(
itemCount: _users == null ? 0 : _users.length,
itemBuilder: (context, index) {
UserModel user = _users[index];
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
ListTile(
title: Text('${user.name} ${user.address.city} ${user.address.geo.lat}'),
subtitle: Text(user.email),
trailing: Text(user.phone),
),
],
);
},
),
),
);
}
}

Related

How can i pass this complex Json MAP Data into flutter Listview

i am new to flutter, and i meet this API with complex "MAP" json. What i want is to display the list of countries with their details in flutter listview, How can i achieve that? Most of answers explain about "LIST" json.
{
"status": "Request is successful",
"message": null,
"data": {
"page": 1,
"last_page": 125,
"page_size": 2,
"countries": [
{
"id": "1",
"attributes": {
"name": "Grenada",
"code": "GD",
"subregion": "Caribbean",
"flag": "https://flagcdn.com/gd.svg",
"postalcode": "",
"latitude": "12.11666666",
"longitude": "-61.66666666",
"createdAt": "2023-01-11T22:15:40.000000Z",
"updatedAt": "2023-01-11T22:15:40.000000Z"
}
},
{
"id": "2",
"attributes": {
"name": "Malaysia",
"code": "MY",
"subregion": "South-Eastern Asia",
"flag": "https://flagcdn.com/my.svg",
"postalcode": "^(\\d{5})$",
"latitude": "2.5",
"longitude": "112.5",
"createdAt": "2023-01-11T22:15:40.000000Z",
"updatedAt": "2023-01-11T22:15:40.000000Z"
}
}
]
}
}
I found this GitHub project with these files json, modelClass Mainclass which relate with the concept but mine is has got one extra braces (map) so i do not know how to achieve the goal.
if there any suggestion or best way to code please help me.
this is how they created in model class but, but it does not work with me.
class Product {
final List<Result> results;
Product({this.results});
factory Product.fromJson(Map<String, dynamic> data) {
var list = data['data']['result'] as List;
List<Result> resultList = list.map((e) => Result.fromJson(e)).toList();
return Product(
results: resultList,
);
}
}
what i have done is
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
var data_from_link;
getData() async {
final String link = 'myurl';
data_from_link = await http.get(Uri.parse(link), headers: {"Accept": "application/json"});
final res = jsonDecode(data_from_link.body) as Map<String, dynamic>;
final List<Country> list= (res['data']['countries'] as List<dynamic>).map((e) => Country.fromJson(e))
.toList();
}
#override
void initState() {
super.initState();
getData();
}
#override
Widget build(BuildContext context) {
final res = jsonDecode(data_from_link.body) as Map<String, dynamic>;
final List<Country> list= (res['data']['countries'] as List<dynamic>).map((e) => Country.fromJson(e))
.toList();
return ListView.builder(
itemCount: list.length,
itemBuilder: (_, i) => ListTile(
title: Text(
list![i].attributes.name,
),
subtitle: Text(list![i].attributes.code),
)
);
}
}
You can create two classes for Country and Attribute
class Country {
const Country({required this.id, required this.attributes});
/// Creates a Country from Json map
factory Country.fromJson(Map<String, dynamic> json) => Country(
id: json['id'] as String,
attribute:
Attribute.fromJson(json['attributes'] as Map<String, dynamic>),
);
/// A description for id
final String id;
final Attribute attributes;
}
class Attribute {
const Attribute({
required this.name,
required this.code,
required this.createdAt,
required this.updatedAt,
});
/// Creates a Attribute from Json map
factory Attribute.fromJson(Map<String, dynamic> json) => Attribute(
name: json['name'] as String,
code: json['code'] as String,
createdAt: DateTime.parse(json['createdAt'] as String),
updatedAt: DateTime.parse(json['updatedAt'] as String),
);
final String name;
final String code;
final DateTime createdAt;
final DateTime updatedAt;
}
when decoding:
final res = jsonDecode(json) as Map<String, dynamic>;
final List<Country> list = (res['data']['countries'] as
List<dynamic>)
.map((e) => Country.fromJson(e))
.toList();
Thank you but how can i print or call data from country attribute
after decoding because when i try something like Print
(list.country.attribute.name) . I fail. My goal is to display on
Listview
You can use it like this:
ListView.builder(
itemCount: list.length,
itemBuilder: (_, i) => ListTile(
title: Text(
list[i].attributes.name,
),
subtitle: Text(list[i].attributes.code),
)),
UPDATE
import 'package:flutter/material.dart';
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
late Future<List<Country>> futureList;
Future<List<Country>?> getData() async {
final String link = 'yoururl';
final res = await http
.get(Uri.parse(link), headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
final List<Country> list = (res['data']['countries'] as List<dynamic>)
.map((e) => Country.fromJson(e))
.toList();
return list;
} else {
throw Exception('Failed to fetch data');
}
}
#override
void initState() {
super.initState();
futureList = getData();
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: futureList,
builder: (context, snapshot) {
if (snapshot.hasData) {
final list = snapshot.data;
return ListView.builder(
itemCount: list!.length,
itemBuilder: (_, i) => ListTile(
title: Text(
list![i].attributes.name,
),
subtitle: Text(list![i].attributes.code),
),
);
} else if (snapshot.hasError) {
return const Text('error fetching data');
}
return const CircularProgressIndicator();
},
);
}
}

How to setState JSON in DropDownField?

// ignore_for_file: prefer_const_constructors, avoid_unnecessary_containers, prefer_const_literals_to_create_immutables, import_of_legacy_library_into_null_safe, non_constant_identifier_names, unused_field, avoid_print
import 'dart:convert';
import 'package:dropdownfield/dropdownfield.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class FoodWidget extends StatefulWidget {
const FoodWidget({Key? key}) : super(key: key);
#override
_FoodWidgetState createState() => _FoodWidgetState();
}
class _FoodWidgetState extends State<FoodWidget> {
#override
void initState() {
fetchFood();
super.initState();
}
String? food_id;
List food = [];
Future<void> fetchFood() async {
final String response =
await rootBundle.loadString('assets/list_food.json');
final data = await json.decode(response);
print(data);
setState(() {
food = data["food"];
});
}
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(15.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
DropDownField(
onValueChanged: (dynamic value) {
food_id = value;
},
value: food_id,
required: false,
labelText: 'Search food',
items: food,
),
]),
);
}
}
and this is the JSON file. I want to get only names in DropDownField but I can't do it. At the setState function, I really don't know how to put it.
{
"food": [
{
"id": 1,
"name": "coca-cola",
"calories": 120
},
{
"id": 2,
"name": "egg",
"calories": 80
},
{
"id": 3,
"name": "rice",
"calories": 100
}
]
}
I tried to print(data) to test the output. It's all coming out of the domain name, but I want to use that inside. And I really don't know how to do it.
PS. I really will appreciate with answers and suggestions.
you would just need to map the data to get only its name :
Future<void> fetchFood() async {
final String response =
await rootBundle.loadString('assets/list_food.json');
final data = await json.decode(response);
print(data);
setState(() {
food = data["food"].map((e)=>e['name']).toList();
});
}
There after getting the list of foods, you map each item to get only the food name, which is what you need.
As a sidenote
I would recommend that in the future you create a model like :
class Food {
Food({
this.id,
this.name,
this.calories,
});
int id;
String name;
int calories;
factory Food.fromJson(Map<String, dynamic> json) => Food(
id: json["id"],
name: json["name"],
calories: json["calories"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"calories": calories,
};
}
So you have a strongly typed List<Food> food and you could access parameters in a type safe matter.
You need to Generate Food class
class Food {
String? id;
String? name;
String? calories;
Food({
this.id,
this.name,
this.calories,
});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'calories': calories,
};
}
factory Food.fromMap(Map<String, dynamic> map) {
return Food(
id: map['id'],
name: map['name'],
calories: map['calories'],
);
}
String toJson() => json.encode(toMap());
factory Food.fromJson(String source) => Food.fromMap(json.decode(source));
}
Full Code here:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class FoodWidget extends StatefulWidget {
const FoodWidget({Key? key}) : super(key: key);
#override
_FoodWidgetState createState() => _FoodWidgetState();
}
class _FoodWidgetState extends State<FoodWidget> {
#override
void initState() {
fetchFood();
super.initState();
}
String? food_id;
Food? selected_food ;
List<Food> food = [];
Future<void> fetchFood() async {
final String response =
await rootBundle.loadString('assets/list_food.json');
final data = await json.decode(response) as List;
print(data);
setState(() {
food = data.map((e) => Food.fromJson(e)).toList();
});
}
#override
Widget build(BuildContext context) {
return Container(
padding:const EdgeInsets.all(15.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
DropdownButton<Food>(
focusColor: Colors.white,
value: selected_food,
//elevation: 5,
style: const TextStyle(color: Colors.white),
iconEnabledColor: Colors.black,
underline: const SizedBox.shrink(),
items: food.map<DropdownMenuItem<Food>>(
(Food value) {
return DropdownMenuItem<Food>(
value: value,
child: Text(
value.name!,
style: const TextStyle(color: Colors.black),
),
);
}).toList(),
hint: const Text(
"Select Shop Category",
style: TextStyle(
color: Colors.black38,
),
),
onChanged: (Food? value) {
setState(() {
selected_food= value!;
});
},
),
]),
);
}
}
class Food {
String? id;
String? name;
String? calories;
Food({
this.id,
this.name,
this.calories,
});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'calories': calories,
};
}
factory Food.fromMap(Map<String, dynamic> map) {
return Food(
id: map['id'],
name: map['name'],
calories: map['calories'],
);
}
String toJson() => json.encode(toMap());
factory Food.fromJson(String source) =>
Food.fromMap(json.decode(source));
}

Error: Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'int' in Flutter

I'm new to Flutter and trying to authenticate an user but I'm facing an error even receiving a response status 200 in the terminal, so I can't navigate to the authorized page.
Please anyone can help me?
Login-Screen code:
import 'package:celer_pesquisa_app/constantes.dart';
import 'package:celer_pesquisa_app/services/login_api.dart';
import 'package:celer_pesquisa_app/telas/recuperar_senha_tela.dart';
import 'package:celer_pesquisa_app/telas/iniciar_quiz_tela.dart';
import 'package:celer_pesquisa_app/utilidades/alert.dart';
import 'package:flutter/material.dart';
class LoginTela extends StatefulWidget {
static const String id = 'login_tela';
#override
_LoginTelaState createState() => _LoginTelaState();
}
class _LoginTelaState extends State<LoginTela> {
String email;
String password;
final _ctrlLogin = TextEditingController();
final _ctrlSenha = TextEditingController();
final _formKey = GlobalKey<FormState>();
_textFormField(
String label,
String hint, {
bool senha = false,
TextEditingController controller,
FormFieldValidator<String> validator,
}) {
return TextFormField(
style: kTextCorEscuro,
controller: controller,
validator: validator,
obscureText: senha,
decoration: InputDecoration(
labelText: label,
labelStyle: TextStyle(
color: kButtonCor2,
),
hintText: hint,
contentPadding:
EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: kButtonCor1, width: 1.0),
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: kButtonCor1, width: 2.0),
borderRadius: BorderRadius.all(Radius.circular(32.0)),
)),
);
}
String _validaLogin(String texto) {
if (texto.isEmpty) {
return 'Digite o email';
}
if (texto.length < 3) {
return 'Email muito curto, insira novamente!';
}
return null;
}
String _validaSenha(String texto) {
if (texto.isEmpty) {
return "Digite o senha";
}
return null;
}
void _clickButton(BuildContext context) async {
bool formOk = _formKey.currentState.validate();
if (!formOk) {
return;
}
String login = _ctrlLogin.text;
String senha = _ctrlSenha.text;
print('login: $login senha: $senha');
var user = await LoginApi.login(login, senha);
if (user != null) {
//print('==> $user');
_navegaQuizStart(context);
} else {
alert(context, "Login Inválido!");
}
}
_navegaQuizStart(BuildContext context) {
Navigator.pushNamed(context, IniciarQuiz.id);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
elevation: 0,
leading: FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: Icon(
Icons.arrow_back_ios,
size: 50.0,
color: kButtonCor2,
),
),
),
backgroundColor: Colors.white,
body: Form(
key: _formKey,
child: ListView(children: [
Padding(
padding: EdgeInsets.symmetric(horizontal: 24.0),
child: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
height: 48.0,
),
_textFormField('Login', 'Digite o email',
controller: _ctrlLogin, validator: _validaLogin),
SizedBox(
height: 8.0,
),
_textFormField('Senha', 'Digite a senha',
senha: true,
controller: _ctrlSenha,
validator: _validaSenha),
SizedBox(
height: 24.0,
),
Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: Material(
color: kButtonCor1,
borderRadius: BorderRadius.all(Radius.circular(30.0)),
elevation: 5.0,
child: MaterialButton(
onPressed: () {
_clickButton(context);
},
minWidth: 200.0,
height: 42.0,
child: Text(
'Entrar',
style: kTextCorClaro,
),
),
),
),
Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: Material(
color: kButtonCor2,
borderRadius: BorderRadius.circular(30.0),
elevation: 5.0,
child: MaterialButton(
onPressed: () {
Navigator.pushNamed(context, RecuperarSenhaTela.id);
},
minWidth: 200.0,
height: 42.0,
child: Text(
'Esqueci a Senha',
style: kTextCorClaro,
),
),
),
),
],
),
),
),
]),
),
);
}
}
Login-api code:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:celer_pesquisa_app/services/user_info.dart';
class LoginApi {
static Future<UserInfo> login(String username, String password) async {
final baseUrl = 'https://iopoc.celer.ind.br:8080/api/v1/';
var url = '$baseUrl/auth/user/login/';
//Content-Type
var header = {
"Content-Type": "application/json",
"Authorization": "Token <TOKEN>"
};
//Body
Map params = {"username": username, "password": password};
var userInfo;
var _body = json.encode(params);
var response = await http.post(url, headers: header, body: _body);
print('Response status: ${response.statusCode}');
//print('Response body: ${response.body}');
Map mapResponse = json.decode(response.body);
if (response.statusCode == 200)
userInfo = UserInfo.fromJson(mapResponse);
} else {
userInfo = null;
}
return userInfo;
}
}
Class UserInfo:
class UserInfo {
UserInfo({
this.user,
this.token,
});
User user;
String token;
factory UserInfo.fromRawJson(String str) =>
UserInfo.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory UserInfo.fromJson(Map<String, dynamic> json) => UserInfo(
user: User.fromJson(json["user"]),
token: json["token"],
);
Map<String, dynamic> toJson() => {
"user": user.toJson(),
"token": token,
};
String toString() {
return 'User(token: $token, user: $user )';
}
}
class User {
User({
this.id,
this.fullName,
this.email,
this.profile,
this.phones,
this.company,
this.tads,
this.createDate,
this.createUser,
this.lastUpdateDate,
this.lastUpdateUser,
this.isActive,
});
int id;
String fullName;
String email;
String profile;
List<Phone> phones;
Company company;
List<dynamic> tads;
DateTime createDate;
AteUser createUser;
DateTime lastUpdateDate;
AteUser lastUpdateUser;
bool isActive;
factory User.fromRawJson(String str) => User.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory User.fromJson(Map<String, dynamic> json) => User(
id: json["id"],
fullName: json["fullName"],
email: json["email"],
profile: json["profile"],
phones: List<Phone>.from(json["phones"].map((x) => Phone.fromJson(x))),
company: Company.fromJson(json["company"]),
tads: List<dynamic>.from(json["tads"].map((x) => x)),
createDate: DateTime.parse(json["createDate"]),
createUser: AteUser.fromJson(json["createUser"]),
lastUpdateDate: DateTime.parse(json["lastUpdateDate"]),
lastUpdateUser: AteUser.fromJson(json["lastUpdateUser"]),
isActive: json["isActive"],
);
Map<String, dynamic> toJson() => {
"id": id,
"fullName": fullName,
"email": email,
"profile": profile,
"phones": List<dynamic>.from(phones.map((x) => x.toJson())),
"company": company.toJson(),
"tads": List<dynamic>.from(tads.map((x) => x)),
"createDate": createDate.toIso8601String(),
"createUser": createUser.toJson(),
"lastUpdateDate": lastUpdateDate.toIso8601String(),
"lastUpdateUser": lastUpdateUser.toJson(),
"isActive": isActive,
};
}
class Company {
Company({
this.id,
this.name,
this.cnpj,
this.email,
this.responsibleName,
this.responsibleEmail,
this.responsiblePhone,
this.street,
this.number,
this.complement,
this.neighborhood,
this.city,
this.state,
this.country,
this.zipcode,
this.phones,
this.branch,
this.createDate,
this.createUser,
this.lastUpdateDate,
this.lastUpdateUser,
this.isActive,
});
int id;
String name;
String cnpj;
String email;
String responsibleName;
String responsibleEmail;
String responsiblePhone;
dynamic street;
dynamic number;
dynamic complement;
dynamic neighborhood;
dynamic city;
dynamic state;
dynamic country;
dynamic zipcode;
List<dynamic> phones;
dynamic branch;
DateTime createDate;
AteUser createUser;
DateTime lastUpdateDate;
AteUser lastUpdateUser;
bool isActive;
factory Company.fromRawJson(String str) => Company.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Company.fromJson(Map<String, dynamic> json) => Company(
id: json["id"],
name: json["name"],
cnpj: json["cnpj"],
email: json["email"],
responsibleName: json["responsibleName"],
responsibleEmail: json["responsibleEmail"],
responsiblePhone: json["responsiblePhone"],
street: json["street"],
number: json["number"],
complement: json["complement"],
neighborhood: json["neighborhood"],
city: json["city"],
state: json["state"],
country: json["country"],
zipcode: json["zipcode"],
phones: List<dynamic>.from(json["phones"].map((x) => x)),
branch: json["branch"],
createDate: DateTime.parse(json["createDate"]),
createUser: AteUser.fromJson(json["createUser"]),
lastUpdateDate: DateTime.parse(json["lastUpdateDate"]),
lastUpdateUser: AteUser.fromJson(json["lastUpdateUser"]),
isActive: json["isActive"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"cnpj": cnpj,
"email": email,
"responsibleName": responsibleName,
"responsibleEmail": responsibleEmail,
"responsiblePhone": responsiblePhone,
"street": street,
"number": number,
"complement": complement,
"neighborhood": neighborhood,
"city": city,
"state": state,
"country": country,
"zipcode": zipcode,
"phones": List<dynamic>.from(phones.map((x) => x)),
"branch": branch,
"createDate": createDate.toIso8601String(),
"createUser": createUser.toJson(),
"lastUpdateDate": lastUpdateDate.toIso8601String(),
"lastUpdateUser": lastUpdateUser.toJson(),
"isActive": isActive,
};
}
class AteUser {
AteUser({
this.id,
this.createDate,
this.lastUpdateDate,
this.isActive,
this.fullName,
this.profile,
this.createUser,
this.lastUpdateUser,
this.user,
this.company,
this.tads,
this.email,
});
int id;
DateTime createDate;
DateTime lastUpdateDate;
bool isActive;
String fullName;
String profile;
int createUser;
int lastUpdateUser;
int user;
int company;
List<dynamic> tads;
String email;
factory AteUser.fromRawJson(String str) => AteUser.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory AteUser.fromJson(Map<String, dynamic> json) => AteUser(
id: json["id"],
createDate: DateTime.parse(json["createDate"]),
lastUpdateDate: DateTime.parse(json["lastUpdateDate"]),
isActive: json["isActive"],
fullName: json["fullName"],
profile: json["profile"],
createUser: json["createUser"],
lastUpdateUser: json["lastUpdateUser"],
user: json["user"],
company: json["company"] == null ? null : json["company"],
tads: List<dynamic>.from(json["tads"].map((x) => x)),
email: json["email"] == null ? null : json["email"],
);
Map<String, dynamic> toJson() => {
"id": id,
"createDate": createDate.toIso8601String(),
"lastUpdateDate": lastUpdateDate.toIso8601String(),
"isActive": isActive,
"fullName": fullName,
"profile": profile,
"createUser": createUser,
"lastUpdateUser": lastUpdateUser,
"user": user,
"company": company == null ? null : company,
"tads": List<dynamic>.from(tads.map((x) => x)),
"email": email == null ? null : email,
};
}
class Phone {
Phone({
this.phone,
this.description,
});
String phone;
String description;
factory Phone.fromRawJson(String str) => Phone.fromJson(json.decode(str));
String toRawJson() => json.encode(toJson());
factory Phone.fromJson(Map<String, dynamic> json) => Phone(
phone: json["phone"],
description: json["description"],
);
Map<String, dynamic> toJson() => {
"phone": phone,
"description": description,
};
}
Postman with the json:
My json
And the error: Terminal error
Thanks so much in advance!!
You have declared "user" as int in "AteUser" model. But the incoming value seems to be JSON. That's why it is throwing the exception. I don't see any key named "user" in your given json screenshot. Maybe in some response, you are getting it as a dictionary, not an integer.

Stuck in CircularProgressIndicator when Fetching data from json API in flutter

I'm debugging an app on my physical device to fetch data from a json API but it keeps showing the CircularProgressIndicator as you see . Still a beginner and I've been trying to solve this for 3 days countinously . Thanks in advance, the code is below
here
main.dart code
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:json/pages/homePage.dart';
void main() {
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.dumpErrorToConsole(details);
if (kReleaseMode) exit(1);
};
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomePage(),
);
}
}
homePage.dart file
import 'package:json/models/bcNewsModel.dart';
import 'package:json/services/api_manager.dart';
class HomePage extends StatefulWidget {
#override
MyHomePage createState() => MyHomePage();
// TODO: implement createState
}
class MyHomePage extends State<HomePage> {
Future<Bitcoin> _bcNews;
#override
void initeState() {
_bcNews = API_Manager().BCNews();
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text('BitCoin App'),
),
body: Container(
child: FutureBuilder<Bitcoin>(
future: _bcNews,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.articles.length,
// ignore: missing_return
itemBuilder: (context, index) {
var article = snapshot.data.articles[index];
Container(
height: 100,
child: Row(
children: <Widget>[
Image.network(article.urlToImage),
],
),
);
});
} else
return Center(child: CircularProgressIndicator());
},
),
));
}
}
api_manager.dart file
Bitcoin bitcoinFromJson(String str) => Bitcoin.fromJson(json.decode(str));
String bitcoinToJson(Bitcoin data) => json.encode(data.toJson());
class Bitcoin {
Bitcoin({
this.status,
this.totalResults,
this.articles,
});
String status;
int totalResults;
List<Article> articles;
factory Bitcoin.fromJson(Map<String, dynamic> json) => Bitcoin(
status: json["status"],
totalResults: json["totalResults"],
articles: List<Article>.from(
json["articles"].map((x) => Article.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"totalResults": totalResults,
"articles": List<dynamic>.from(articles.map((x) => x.toJson())),
};
}
class Article {
Article({
this.source,
this.author,
this.title,
this.description,
this.url,
this.urlToImage,
this.publishedAt,
this.content,
});
Source source;
String author;
String title;
String description;
String url;
String urlToImage;
DateTime publishedAt;
String content;
factory Article.fromJson(Map<String, dynamic> json) => Article(
source: Source.fromJson(json["source"]),
author: json["author"],
title: json["title"],
description: json["description"],
url: json["url"],
urlToImage: json["urlToImage"],
publishedAt: DateTime.parse(json["publishedAt"]),
content: json["content"],
);
Map<String, dynamic> toJson() => {
"source": source.toJson(),
"author": author,
"title": title,
"description": description,
"url": url,
"urlToImage": urlToImage,
"publishedAt": publishedAt.toIso8601String(),
"content": content,
};
}
class Source {
Source({
this.id,
this.name,
});
String id;
String name;
factory Source.fromJson(Map<String, dynamic> json) => Source(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
Could the problem be with my physical device ?
Since you are trying to request this information, check in your manifest if you have enabled access to the internet. Otherwise, it will keep on blocking the requests.

Flutter fetch data from the internet

I'm trying to get some information from here such as name,avatar_url,stargazers_count and description
{
"total_count": 18689015,
"incomplete_results": true,
"items": [
{
"id": 215415332,
"node_id": "MDEwOlJlcG9zaXRvcnkyMTU0MTUzMzI=",
"name": "HackingNeuralNetworks",
"full_name": "Kayzaks/HackingNeuralNetworks",
"private": false,
"owner": {
"login": "Kayzaks",
"id": 11071537,
"node_id": "MDQ6VXNlcjExMDcxNTM3",
"avatar_url": "https://avatars1.githubusercontent.com/u/11071537?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/Kayzaks",
"html_url": "https://github.com/Kayzaks",
"followers_url": "https://api.github.com/users/Kayzaks/followers",
"following_url": "https://api.github.com/users/Kayzaks/following{/other_user}",
"gists_url": "https://api.github.com/users/Kayzaks/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Kayzaks/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Kayzaks/subscriptions",
"organizations_url": "https://api.github.com/users/Kayzaks/orgs",
"repos_url": "https://api.github.com/users/Kayzaks/repos",
"events_url": "https://api.github.com/users/Kayzaks/events{/privacy}",
"received_events_url": "https://api.github.com/users/Kayzaks/received_events",
"type": "User",
"site_admin": false
},
"html_url": "https://github.com/Kayzaks/HackingNeuralNetworks",
"description": "A small course on exploiting and defending neural networks",
"fork": false,
....
....
At run time I get this message error :
type _internalLine HashMap<String , dynamic> is not a subtype of type List<dynamic> in type cast
here's the full code :
RepoItem:
class RepoItem {
Owner owner;
String name;
String stargazers_count;
String description;
RepoItem._({this.owner, this.name, this.stargazers_count, this.description});
factory RepoItem.fromJson(Map<String, dynamic> json) {
return new RepoItem._(
owner: json['owner'],
name: json['name'],
stargazers_count: json['stargazers_count'],
description: json['description']);
}
}
PageState:
class _MyHomePageState extends State<MyHomePage> {
List<RepoItem> list = List();
var isLoading = false;
Future<List<RepoItem>> _fetchData() async {
final response = await http.get(
"https://api.github.com/search/repositories?q=created:%3E2018-10-22&sort=stars&order=desc");
list = (json.decode(response.body) as List)
.map((data) => new RepoItem.fromJson(data.body))
.toList();
return list;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
child: FutureBuilder(
future: _fetchData(),
builder: (BuildContext context, AsyncSnapshot asyncSnapshot) {
if (asyncSnapshot.hasError) {
return Container(
child: Center(
child: Text(asyncSnapshot.error.toString()),
),
);
}
if (asyncSnapshot.data == null) {
return Container(
child: Center(
child: Text("Loading ..."),
),
);
} else {
return ListView.builder(
itemCount: asyncSnapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(asyncSnapshot.data[index].name),
leading: CircleAvatar(
backgroundImage: NetworkImage(
asyncSnapshot.data[index].owner.avatar_url),
),
subtitle: Text(asyncSnapshot.data[index].description),
);
},
);
}
},
),
),
);
}
}
You can copy paste run full code below
You can parse with payloadFromJson, you can see Payload class in full code
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
...
var items = snapshot.data.items;
return ListView.builder(
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(items[index].name),
leading: CircleAvatar(
backgroundImage:
NetworkImage(items[index].owner.avatarUrl),
),
subtitle: Text(items[index].description),
);
},
);
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
String totalCount;
bool incompleteResults;
List<Item> items;
Payload({
this.totalCount,
this.incompleteResults,
this.items,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
totalCount: json["total_count"].toString(),
incompleteResults: json["incomplete_results"],
items: List<Item>.from(json["items"].map((x) => Item.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"total_count": totalCount,
"incomplete_results": incompleteResults,
"items": List<dynamic>.from(items.map((x) => x.toJson())),
};
}
class Item {
String id;
String nodeId;
String name;
String fullName;
bool private;
Owner owner;
String htmlUrl;
String description;
bool fork;
String url;
String forksUrl;
String keysUrl;
String collaboratorsUrl;
String teamsUrl;
String hooksUrl;
String issueEventsUrl;
String eventsUrl;
String assigneesUrl;
String branchesUrl;
String tagsUrl;
String blobsUrl;
String gitTagsUrl;
String gitRefsUrl;
String treesUrl;
String statusesUrl;
String languagesUrl;
String stargazersUrl;
String contributorsUrl;
String subscribersUrl;
String subscriptionUrl;
String commitsUrl;
String gitCommitsUrl;
String commentsUrl;
String issueCommentUrl;
String contentsUrl;
String compareUrl;
String mergesUrl;
String archiveUrl;
String downloadsUrl;
String issuesUrl;
String pullsUrl;
String milestonesUrl;
String notificationsUrl;
String labelsUrl;
String releasesUrl;
String deploymentsUrl;
DateTime createdAt;
DateTime updatedAt;
DateTime pushedAt;
String gitUrl;
String sshUrl;
String cloneUrl;
String svnUrl;
String homepage;
int size;
int stargazersCount;
int watchersCount;
String language;
bool hasIssues;
bool hasProjects;
bool hasDownloads;
bool hasWiki;
bool hasPages;
int forksCount;
dynamic mirrorUrl;
bool archived;
bool disabled;
int openIssuesCount;
License license;
int forks;
int openIssues;
int watchers;
DefaultBranch defaultBranch;
double score;
Item({
this.id,
this.nodeId,
this.name,
this.fullName,
this.private,
this.owner,
this.htmlUrl,
this.description,
this.fork,
this.url,
this.forksUrl,
this.keysUrl,
this.collaboratorsUrl,
this.teamsUrl,
this.hooksUrl,
this.issueEventsUrl,
this.eventsUrl,
this.assigneesUrl,
this.branchesUrl,
this.tagsUrl,
this.blobsUrl,
this.gitTagsUrl,
this.gitRefsUrl,
this.treesUrl,
this.statusesUrl,
this.languagesUrl,
this.stargazersUrl,
this.contributorsUrl,
this.subscribersUrl,
this.subscriptionUrl,
this.commitsUrl,
this.gitCommitsUrl,
this.commentsUrl,
this.issueCommentUrl,
this.contentsUrl,
this.compareUrl,
this.mergesUrl,
this.archiveUrl,
this.downloadsUrl,
this.issuesUrl,
this.pullsUrl,
this.milestonesUrl,
this.notificationsUrl,
this.labelsUrl,
this.releasesUrl,
this.deploymentsUrl,
this.createdAt,
this.updatedAt,
this.pushedAt,
this.gitUrl,
this.sshUrl,
this.cloneUrl,
this.svnUrl,
this.homepage,
this.size,
this.stargazersCount,
this.watchersCount,
this.language,
this.hasIssues,
this.hasProjects,
this.hasDownloads,
this.hasWiki,
this.hasPages,
this.forksCount,
this.mirrorUrl,
this.archived,
this.disabled,
this.openIssuesCount,
this.license,
this.forks,
this.openIssues,
this.watchers,
this.defaultBranch,
this.score,
});
factory Item.fromJson(Map<String, dynamic> json) => Item(
id: json["id"].toString(),
nodeId: json["node_id"],
name: json["name"],
fullName: json["full_name"],
private: json["private"],
owner: Owner.fromJson(json["owner"]),
htmlUrl: json["html_url"],
description: json["description"] == null ? null : json["description"],
fork: json["fork"],
url: json["url"],
forksUrl: json["forks_url"],
keysUrl: json["keys_url"],
collaboratorsUrl: json["collaborators_url"],
teamsUrl: json["teams_url"],
hooksUrl: json["hooks_url"],
issueEventsUrl: json["issue_events_url"],
eventsUrl: json["events_url"],
assigneesUrl: json["assignees_url"],
branchesUrl: json["branches_url"],
tagsUrl: json["tags_url"],
blobsUrl: json["blobs_url"],
gitTagsUrl: json["git_tags_url"],
gitRefsUrl: json["git_refs_url"],
treesUrl: json["trees_url"],
statusesUrl: json["statuses_url"],
languagesUrl: json["languages_url"],
stargazersUrl: json["stargazers_url"],
contributorsUrl: json["contributors_url"],
subscribersUrl: json["subscribers_url"],
subscriptionUrl: json["subscription_url"],
commitsUrl: json["commits_url"],
gitCommitsUrl: json["git_commits_url"],
commentsUrl: json["comments_url"],
issueCommentUrl: json["issue_comment_url"],
contentsUrl: json["contents_url"],
compareUrl: json["compare_url"],
mergesUrl: json["merges_url"],
archiveUrl: json["archive_url"],
downloadsUrl: json["downloads_url"],
issuesUrl: json["issues_url"],
pullsUrl: json["pulls_url"],
milestonesUrl: json["milestones_url"],
notificationsUrl: json["notifications_url"],
labelsUrl: json["labels_url"],
releasesUrl: json["releases_url"],
deploymentsUrl: json["deployments_url"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
pushedAt: DateTime.parse(json["pushed_at"]),
gitUrl: json["git_url"],
sshUrl: json["ssh_url"],
cloneUrl: json["clone_url"],
svnUrl: json["svn_url"],
homepage: json["homepage"] == null ? null : json["homepage"],
size: json["size"],
stargazersCount: json["stargazers_count"],
watchersCount: json["watchers_count"],
language: json["language"] == null ? null : json["language"],
hasIssues: json["has_issues"],
hasProjects: json["has_projects"],
hasDownloads: json["has_downloads"],
hasWiki: json["has_wiki"],
hasPages: json["has_pages"],
forksCount: json["forks_count"],
mirrorUrl: json["mirror_url"],
archived: json["archived"],
disabled: json["disabled"],
openIssuesCount: json["open_issues_count"],
license:
json["license"] == null ? null : License.fromJson(json["license"]),
forks: json["forks"],
openIssues: json["open_issues"],
watchers: json["watchers"],
defaultBranch: defaultBranchValues.map[json["default_branch"]],
score: json["score"],
);
Map<String, dynamic> toJson() => {
"id": id,
"node_id": nodeId,
"name": name,
"full_name": fullName,
"private": private,
"owner": owner.toJson(),
"html_url": htmlUrl,
"description": description == null ? null : description,
"fork": fork,
"url": url,
"forks_url": forksUrl,
"keys_url": keysUrl,
"collaborators_url": collaboratorsUrl,
"teams_url": teamsUrl,
"hooks_url": hooksUrl,
"issue_events_url": issueEventsUrl,
"events_url": eventsUrl,
"assignees_url": assigneesUrl,
"branches_url": branchesUrl,
"tags_url": tagsUrl,
"blobs_url": blobsUrl,
"git_tags_url": gitTagsUrl,
"git_refs_url": gitRefsUrl,
"trees_url": treesUrl,
"statuses_url": statusesUrl,
"languages_url": languagesUrl,
"stargazers_url": stargazersUrl,
"contributors_url": contributorsUrl,
"subscribers_url": subscribersUrl,
"subscription_url": subscriptionUrl,
"commits_url": commitsUrl,
"git_commits_url": gitCommitsUrl,
"comments_url": commentsUrl,
"issue_comment_url": issueCommentUrl,
"contents_url": contentsUrl,
"compare_url": compareUrl,
"merges_url": mergesUrl,
"archive_url": archiveUrl,
"downloads_url": downloadsUrl,
"issues_url": issuesUrl,
"pulls_url": pullsUrl,
"milestones_url": milestonesUrl,
"notifications_url": notificationsUrl,
"labels_url": labelsUrl,
"releases_url": releasesUrl,
"deployments_url": deploymentsUrl,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
"pushed_at": pushedAt.toIso8601String(),
"git_url": gitUrl,
"ssh_url": sshUrl,
"clone_url": cloneUrl,
"svn_url": svnUrl,
"homepage": homepage == null ? null : homepage,
"size": size,
"stargazers_count": stargazersCount,
"watchers_count": watchersCount,
"language": language == null ? null : language,
"has_issues": hasIssues,
"has_projects": hasProjects,
"has_downloads": hasDownloads,
"has_wiki": hasWiki,
"has_pages": hasPages,
"forks_count": forksCount,
"mirror_url": mirrorUrl,
"archived": archived,
"disabled": disabled,
"open_issues_count": openIssuesCount,
"license": license == null ? null : license.toJson(),
"forks": forks,
"open_issues": openIssues,
"watchers": watchers,
"default_branch": defaultBranchValues.reverse[defaultBranch],
"score": score,
};
}
enum DefaultBranch { MASTER }
final defaultBranchValues = EnumValues({"master": DefaultBranch.MASTER});
class License {
String key;
String name;
String spdxId;
String url;
String nodeId;
License({
this.key,
this.name,
this.spdxId,
this.url,
this.nodeId,
});
factory License.fromJson(Map<String, dynamic> json) => License(
key: json["key"],
name: json["name"],
spdxId: json["spdx_id"],
url: json["url"] == null ? null : json["url"],
nodeId: json["node_id"],
);
Map<String, dynamic> toJson() => {
"key": key,
"name": name,
"spdx_id": spdxId,
"url": url == null ? null : url,
"node_id": nodeId,
};
}
class Owner {
String login;
String id;
String nodeId;
String avatarUrl;
String gravatarId;
String url;
String htmlUrl;
String followersUrl;
String followingUrl;
String gistsUrl;
String starredUrl;
String subscriptionsUrl;
String organizationsUrl;
String reposUrl;
String eventsUrl;
String receivedEventsUrl;
Type type;
bool siteAdmin;
Owner({
this.login,
this.id,
this.nodeId,
this.avatarUrl,
this.gravatarId,
this.url,
this.htmlUrl,
this.followersUrl,
this.followingUrl,
this.gistsUrl,
this.starredUrl,
this.subscriptionsUrl,
this.organizationsUrl,
this.reposUrl,
this.eventsUrl,
this.receivedEventsUrl,
this.type,
this.siteAdmin,
});
factory Owner.fromJson(Map<String, dynamic> json) => Owner(
login: json["login"],
id: json["id"].toString(),
nodeId: json["node_id"],
avatarUrl: json["avatar_url"],
gravatarId: json["gravatar_id"],
url: json["url"],
htmlUrl: json["html_url"],
followersUrl: json["followers_url"],
followingUrl: json["following_url"],
gistsUrl: json["gists_url"],
starredUrl: json["starred_url"],
subscriptionsUrl: json["subscriptions_url"],
organizationsUrl: json["organizations_url"],
reposUrl: json["repos_url"],
eventsUrl: json["events_url"],
receivedEventsUrl: json["received_events_url"],
type: typeValues.map[json["type"]],
siteAdmin: json["site_admin"],
);
Map<String, dynamic> toJson() => {
"login": login,
"id": id,
"node_id": nodeId,
"avatar_url": avatarUrl,
"gravatar_id": gravatarId,
"url": url,
"html_url": htmlUrl,
"followers_url": followersUrl,
"following_url": followingUrl,
"gists_url": gistsUrl,
"starred_url": starredUrl,
"subscriptions_url": subscriptionsUrl,
"organizations_url": organizationsUrl,
"repos_url": reposUrl,
"events_url": eventsUrl,
"received_events_url": receivedEventsUrl,
"type": typeValues.reverse[type],
"site_admin": siteAdmin,
};
}
enum Type { USER, ORGANIZATION }
final typeValues =
EnumValues({"Organization": Type.ORGANIZATION, "User": Type.USER});
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
static final String URL = "https://corona.lmao.ninja/countries";
Future _future;
Future<Payload> _fetchData() async {
final response = await http.get(
"https://api.github.com/search/repositories?q=created:%3E2018-10-22&sort=stars&order=desc");
var list = payloadFromJson(response.body);
return list;
}
#override
void initState() {
// TODO: implement initState
super.initState();
_future = _fetchData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder<Payload>(
future: _future,
builder: (BuildContext context, AsyncSnapshot<Payload> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Input a URL to start');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
var items = snapshot.data.items;
return ListView.builder(
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(items[index].name),
leading: CircleAvatar(
backgroundImage:
NetworkImage(items[index].owner.avatarUrl),
),
subtitle: Text(items[index].description),
);
},
);
}
}
}));
}
}