How to access an item from a json through FutureBuilder? - flutter

i'm getting a json and would like to access certain items.
The method below returns the json I need to access.
search(cpf) async {
try {
final response = await http.get(
Uri.parse(BaseUrl.baseUrl + 'api/produtor/serach/$data'));
if (response.statusCode == 200) {
final jsonMap = jsonDecode(response.body) as Map<String, dynamic>;
final user = User.fromJson(jsonMap);
return user;
} else {
throw Exception("Error");
}
} catch (e) {
throw Exception(e.toString());
}
}
I created this example to try to access the items.
Future? _list;
#override
void initState() {
super.initState();
_list = widget.produtorServices.buscaProdutorPorCPF("56039891653");
}
Widget build(BuildContext context) {
return new Scaffold(
body: Container(
child: FutureBuilder(
future: widget.produtorServices.buscaProdutorPorCPF("56039891653"),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Text("${snapshot.error}");
}
if (!snapshot.hasData) {
return Text("Null returned");
}
final user = snapshot.data as Produtor;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('${user.id}: ${user.name}'),
],
); //Text(snapshot.data!.ip);
},
),
),
);
}
}
Here is json
[
{
"user":{
"roles":[
"622f533b5ee724631428f469"
],
"_id":"622f78fbf297571510cb4e32",
"nome":"XXXX",
"email":"teste#teste.com"
}
}
]
How do I add eg a text widget and access the json item?
I've already tried to solve using the model too. I declare User user and then I try to access the variable like this: user.name
But I get the error:
Error: Exception: Expected a value of type 'Map<String, dynamic>', but got one of type 'List'
I appreciate if anyone can help me analyze this!

You create two data classes to hold your JSON object.
class Users {
List<User> users;
Users({
required this.users,
});
factory Users.fromJson(Map<String, dynamic> json) => Users(
users: (json['users'] as List<dynamic>)
.map((e) => User.fromJson(e as Map<String, dynamic>))
.toList(),
);
}
class User {
List<String>? roles;
String? id;
String? nome;
String? email;
User({
this.roles,
this.id,
this.nome,
this.email,
});
factory User.fromJson(Map<String, dynamic> json) => User(
roles: (json['roles'] as List<dynamic>?)?.map((e) =>
e as String).toList(),
id: json['id'] as String?,
nome: json['nome'] as String?,
email: json['email'] as String?,
);
}
Then in your search method:
if (response.statusCode == 200) {
final jsonMap = jsonDecode(response.body) as Map<String, dynamic>;
final users = Users.fromJson(jsonMap);
return users;
} else {
throw Exception("Error");
}
In your FutureBuilder:
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Text("${snapshot.error}");
}
if (!snapshot.hasData) {
return Text("Null returned");
}
final userList = snapshot.data as Users;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: List<Text>.generate(
userList.users.length,
(index) {
final user = userList.users[index];
return Text('${user.id}: ${user.nome}, ${user.email}, ${user.roles}');
},
),
); //Text(snapshot.data!.ip);

Related

Flutter type 'Null' is not a subtype of type 'int', trying to get complicated JSON into flutter

This is my json here: https://my-json-server.typicode.com/fluttirci/testJson/db
This code only works if there is an only one json object however, with this employees JSON, it doesn't work. Flutter documentation isn't very clear about this subject. They only work on one line jsons. What I wanna do is, I wanna get all that data into my phone screen. If I get it, I will show them on a table or a grid. But yet it doesn't won't work. It says type 'Null' is not a subtype of type 'int' . Here is my code:
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://my-json-server.typicode.com/fluttirci/testJson/db'));
print(response);
Map<String, dynamic> userMap = jsonDecode(response.body);
if (response.statusCode == 200) {
return Album.fromJson(userMap); //testing
} else {
throw Exception('Failed to load album');
}
}
class Album {
final int userId;
final int id;
final String title;
Album(this.userId, this.id, this.title);
Album.fromJson(Map<String, dynamic> json)
: userId = json['userId'],
id = json['id'],
title = json['title'];
Map<String, dynamic> toJson() => {
'userId': userId,
'id': id,
'title': title,
};
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
late Future<Album> user;
#override
void initState() {
super.initState();
user = fetchAlbum();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
brightness: Brightness.dark,
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Album>(
future: user,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.title);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
),
),
),
);
}
}
Try this:
Future<List<Album>> fetchAlbum() async {
final response = await http.get(
Uri.parse('https://my-json-server.typicode.com/fluttirci/testJson/db'));
print(response);
Map<String, dynamic> userMap = jsonDecode(response.body);
if (response.statusCode == 200) {
return (userMap['employees'] as List).map((e) => Album.fromJson(e)).toList()
} else {
throw Exception('Failed to load album');
}
}
then change your FutureBuilder to this:
FutureBuilder<List<Album>>(
future: user,
builder: (context, snapshot) {
if (snapshot.hasData) {
List<Album> data = snapshot.data ?? [];
return ListView.builder(
itemBuilder: (context, index) {
return Column(children: [
Text(data[index].title ?? ""),
]);
},
itemCount: data.length,
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
)
Your response.body return a list on employees key. And test this model with the response
Future<List<Album>?> fetchAlbum() async {
final response = await http.get(
Uri.parse('https://my-json-server.typicode.com/fluttirci/testJson/db'));
if (response.statusCode == 200) {
final data = jsonDecode(response.body)["employees"] as List?;
return data?.map((e) => Album.fromMap(e)).toList();
} else {
throw Exception('Failed to load album');
}
}
class Album {
final int userId;
final int id;
final String title;
Album(this.userId, this.id, this.title);
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
result.addAll({'userId': userId});
result.addAll({'id': id});
result.addAll({'title': title});
return result;
}
factory Album.fromMap(Map<String, dynamic> map) {
return Album(
map['userId']?.toInt() ?? 0,
map['id']?.toInt() ?? 0,
map['title'] ?? '',
);
}
String toJson() => json.encode(toMap());
factory Album.fromJson(String source) => Album.fromMap(json.decode(source));
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late final user = fetchAlbum();
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder<List<Album>?>(
future: user,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data?.length,
itemBuilder: (context, index) =>
Text("${snapshot.data?[index].title}"),
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
),
),
);
}
}
so the resultMap should look right like this :
{
"employees": [
{
"userId": 1,
"id": 2,
"title": "Doe"
},
{
"userId": 2,
"id": 3,
"title": "Smith"
},
{
"userId": 3,
"id": 4,
"title": "Jones"
}
]
}
This is a map that only has one property, which it values as a List of other maps
so accessing json['userId'] will try to get the userId from that map, which doesn't exist in the map
you need to access the employees property :
json["employees"]
then you get the value of it, which is the nested List of maps, and now you can access an element in the List with its index, then get the userId :
json["employees"][0]["userId"] // 1
json["employees"][1]["userId"] // 2
json["employees"][2]["userId"] // 3
hope this gives you a better approach to what you are trying to do, and what you need to do.
so this :
return Album.fromJson(userMap);
should be replaced with this, as an example:
return Album.fromJson(userMap["employees"][0]);
here the userMap["employees"][0] is :
{
"userId": 1,
"id": 2,
"title": "Doe"
},
and now it should make an Album object from it.
if you want to get a List instead of the List<Map<string, dynamic>>, you need to iterate over the whole list using the map method or with a for loop
hope it helps

Why I can't fetch data by Json on my Flutter App

I wasn't get any data from fake Api : https://jsonplaceholder.typicode.com/users to my flutter App. Can anyone please give me piece of advise why or how I can get those data on my app. For creating the Model file using https://app.quicktype.io/.
JsonModel File:
import 'dart:convert';
List<JsonModel> jsonModelFromJson(String str) =>
List<JsonModel>.from(json.decode(str).map((x) => JsonModel.fromJson(x)));
String jsonModelToJson(List<JsonModel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class JsonModel {
JsonModel({
this.id,
this.name,
this.username,
this.email,
this.address,
this.phone,
this.website,
this.company,
});
int? id;
String? name;
String? username;
String? email;
Address? address;
String? phone;
String? website;
Company? company;
factory JsonModel.fromJson(Map<String, dynamic> json) => JsonModel(
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 {
Address({
this.street,
this.suite,
this.city,
this.zipcode,
this.geo,
});
String? street;
String? suite;
String? city;
String? zipcode;
Geo? 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 {
Geo({
this.lat,
this.lng,
});
String? lat;
String? 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 {
Company({
this.name,
this.catchPhrase,
this.bs,
});
String? name;
String? catchPhrase;
String? 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,
};
}
Service or JsonApi File:
import 'dart:convert';
import 'package:flutter_learning_from_pageview/Model/JsonModel.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
class JsonApi {
bool loading = true;
var json_Data;
Future<JsonModel> getJsonData() async {
var client = http.Client();
String uri = "https://jsonplaceholder.typicode.com/users";
var response = await client.get(Uri.parse(uri));
var jsonModel = null;
try {
if (response.statusCode == 200) {
var decode = json.decode(response.body);
jsonModel = JsonModel.fromJson(decode);
print(jsonModel);
} else {
throw Exception("falied to load");
}
} catch (Exception) {
return jsonModel;
}
return jsonModel;
}
}
Try to call it but As progress bar not closed it mean I didn't get the data
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_learning_from_pageview/Model/JsonModel.dart';
import 'package:flutter_learning_from_pageview/Service/JsonApi.dart';
class JsonData extends StatefulWidget {
const JsonData({Key? key}) : super(key: key);
#override
_JsonDataState createState() => _JsonDataState();
}
class _JsonDataState extends State<JsonData> {
bool loading = true;
Future<JsonModel>? _jsonModel;
#override
void initState() {
_jsonModel = JsonApi().getJsonData();
super.initState();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: FutureBuilder(
future: _jsonModel,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
//itemCount: json_Data == null ? 0 : json_Data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(""),
//subtitle: Text(json_Data[index]["body"]),
);
});
} else {
return Center(child: CircularProgressIndicator());
}
},
),
),
);
}
}
You made some mistake so try to change it to like this. you are trying to parse list of data with just a single element.
class JsonApi {
Future<List<JsonModel>> getJsonData() async {
var client = http.Client();
String uri = "https://jsonplaceholder.typicode.com/users";
var response = await client.get(Uri.parse(uri));
if (response.statusCode == 200) {
return jsonModelFromJson(response.body);
} else {
throw Exception("falied to load");
}
}
}
Then try this code
late final Future<List<JsonModel>> _futureData;
apiCalling() {
_futureData = JsonApi().getJsonData();
}
#override
void initState() {
apiCalling();
super.initState();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: FutureBuilder(
future: _futureData,
builder: (context, AsyncSnapshot<List<JsonModel>> snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.length,
//itemCount: json_Data == null ? 0 : json_Data.length,
itemBuilder: (context, index) {
return ListTile(
onTap: () {
setState(() {});
},
title: Text(snapshot.data![index].name!),
//subtitle: Text(json_Data[index]["body"]),
);
});
} else {
return Center(child: CircularProgressIndicator());
}
},
),
),
);
}
from init state you have to change like this:
#override
void initState() {
callApi();
super.initState();
}
void callApi() async {
_jsonModel = await JsonApi().getJsonData();
}
as you are not calling that with await so, it has no data
I found your issue. You trying to fetch data in wrong jsonModel.
Remove this code
var decode = json.decode(response.body);
jsonModel = JsonModel.fromJson(decode);
Use this Instead
jsonModel = jsonModelFromJson(response.body);
Your Api data is in Array format and you are trying to store in Class format.
Try below code hope its help to you.
Your API Call:
Future<List<dynamic>> getJobsData() async {
String url = 'https://jsonplaceholder.typicode.com/users';
var response = await http.get(Uri.parse(url), headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
});
return json.decode(response.body);
}
Your Widget:
Center(
child: FutureBuilder<List<dynamic>>(
future: getJobsData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListView.builder(
shrinkWrap: true,
physics:const NeverScrollableScrollPhysics(),
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
var id = snapshot.data![index]['id'];
var name = snapshot.data![index]['name'];
var username = snapshot.data![index]['username'];
var email = snapshot.data![index]['email'];
var phone = snapshot.data![index]['phone'];
return Card(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.green.shade300,
),
borderRadius: BorderRadius.circular(15.0),
),
child: ListTile(
leading: Text(id.toString()),
title: Text(name),
subtitle: Text(
username + '\n' + email + '\n' + phone.toString(),
),
),
);
},
),
);
}
return const CircularProgressIndicator();
},
),
),
Refer my answer here and here for get data from json API
Your Result Screen->
Make sure response.body is returning data.
Avoid using ? in futures, otherwise snapshot could be empty the whole time when body is null. The ui will always show loading.
To make your code look more simple:
Inside statefull widget:
late final Future<List<Data>> _futureData;
And in your initState:
#override
void initState(){
_futureData = provider.loadFutureData();
super.initState();
}
Or if you don't are using provider:
#override
void initState(){
_futureData = loadDataFromFunction();
super.initState();
}

how to get data object in flutter

hello i have json data like this
{
"iduser": 3,
"fname": "joni"
}
I want to display it on the home page
Previously I have created a model class below
usermodel.dart
class UserModel {
int id;
String fname;
UserModel(
this.id,
this.fname,
);
UserModel.fromJson(Map<String, dynamic> response) {
id = response['iduser'];
fname = response['fname'];
}
Map<String, dynamic> toJson() {
return {
'id': id,
'fname': fname,
};
}
}
and I created a service page to interact with api
class AuthService {
String baseUrl = 'https://myurl.com';
Future<UserModel> getUser() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var id = prefs.getInt('id');
var token = prefs.getString('token');
var url = '$baseUrl/users/$id';
var headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer $token'
};
var response = await http.get(
Uri.parse(url),
headers: headers,
);
print(response.body);
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
UserModel user = UserModel.fromJson(data);
return user;
} else {
print(response.body);
throw Exception('Failed');
}
}
}
home.dart
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: Center(
child: Text( ), //get json fname
),
);
}
}
before I run but I get error type
'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'FutureOr<List<GetUserModel>>'
how to display the fname I get from the service on the home page?
thank you !
Make home.dart a stateful widget and get the data in initstate and store in a variable. Use that variable to display the data here is how
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
void initState() {
super.initState();
getAsync();
}
UserModel user;
getAsync() async {
try {
user = await AuthService().getUser();
} catch (e) {
print(e);
}
if (mounted) setState(() {});
}
#override
Widget build(BuildContext context) {
if (user == null) return Center(child: CircularProgressIndicator());
else
return Container(
color: Colors.white,
child: Center(
child: Text(user.fname), //get json fname
),
);
}
}
You have two options;
Use FutureBuilder
Convert to StatefullWidget
I give you FutureBuilder example;
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return FutureBuilder<UserModel>(
future: AuthService().getUser(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting: return Text('Loading....');
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
final data = snapshot.data;
return Container(
color: Colors.white,
child: Center(
child: Text(data.fname), //get json fname
),
);
}
}
},
);
}
}
Also, as far as I can see, there is a problem with the id conversion of the fromJson and toJson methods. Related fields should be 'iduser' according to json data.
class UserModel {
int id;
String fname;
UserModel(
this.id,
this.fname,
);
UserModel.fromJson(Map<String, dynamic> response) {
id = response['iduser'];
fname = response['fname'];
}
Map<String, dynamic> toJson() {
return {
'iduser': id,
'fname': fname,
};
}
}
First, you may want to be consistent in your map key to get the desired result.
You have to replace the key of flutter map version from:
id = response['id']; => id = response['iduser'];
or vice versa.
Now in your homepage, you need to instantiate the AuthService class in order to access the function that will get the specified user.
You need to use FutureBuilder in order to automatically update the Text if the data was fetched.
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
AuthService _authService = AuthService();
return Container(
color: Colors.white,
child: FutureBuilder<User>(
future: _authService.getUser(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.firstName);
}
/// Show some loading artifact while fetching the
/// user data from the server.
else {
return CircularProgressIndicator();
}
},
),
);
}
}

Invalid value: Only valid value is 0: 1 in Flutter

I create an UI with FutureBuilder to show an nested object from my rest api, but i don't know why, but after run my function(in my UI) my console throw me this type of error:
RangeError (index): Invalid value: Only valid value is 0: 1
I try flutter doctor but it not help me,
ps. I can't use itemCount: snapshot.data.length because
Class 'User' has no instance getter 'length'
my code:
#override
void initState(){
super.initState();
userApiService = UserApiService();
_future = getUserData();
}
getUserData() async{
sharedPreferences = await SharedPreferences.getInstance();
int id = sharedPreferences.getInt('id');
return userApiService.getUser(id);
}
#override
Widget build(BuildContext context){
return FutureBuilder(
future: _future,
builder: (context, snapshot){
if(!snapshot.hasData){
return Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
// User user = snapshot.data;
return Scaffold(
backgroundColor: Colors.white,
body: Container(
child: ListView.builder(
itemBuilder: (context, i){
User user = snapshot.data;
return GestureDetector(
onTap: () {
//
},
child: Container(
width: 300,
height: 80,
color: Colors.blue,
child: Text(user.myFollows[i].firstName + ' ' + user.myFollows[i].lastName),
),
);
}
)
),
);
},
);
}
model User:
class User {
List<Observations> followedBy;
List<Observations> myFollows;
int id;
String firstName;
String lastName;
User(
{
this.followedBy,
this.myFollows,
this.id,
this.firstName,
this.lastName,
});
factory User.fromJson(Map<String, dynamic> json){
return User(
id: json['id'],
firstName: json['firstName'],
lastName: json['lastName'],
followedBy: parseFollowedBy(json),
myFollows: parseMyFollows(json),
);
}
static List<Observations> parseFollowedBy(json){
var lista = json['followedBy'] as List;
List<Observations> followedByList = lista.map((data) => Observations.fromJson(data)).toList();
return followedByList;
}
static List<Observations> parseMyFollows(myFollowsJson){
var list = myFollowsJson['myFollows'] as List;
List<Observations> myFollowsList = list.map((data) => Observations.fromJson(data)).toList();
return myFollowsList;
}
}
List<User> usersFromJson(String jsonData){
final data = json.decode(jsonData);
return List<User>.from(data.map((item) => User.fromJson(item)));
}
User userFromJson(String jsonData){
final data = json.decode(jsonData);
return User.fromJson(data);
}
String userToJson(User data){
final jsonData = data.toJson();
return json.encode(jsonData);
}
model observations.dart:
class Observations {
final int id;
final String firstName;
final String lastName;
Observations({this.id, this.firstName, this.lastName});
factory Observations.fromJson(Map<String, dynamic> parsedJson) {
return Observations(
id: parsedJson['id'],
firstName: parsedJson['firstName'],
lastName: parsedJson['lastName'],
);
}
}
thanks for any help :)
In this case you have to set itemCount to the lenght of the list you are traversing in the ListView.
I see you are using user.myFollows[i]
So maybe you should use:
itemCount: user.myFollows.length,

Flutter Http call List<t> always result Null in UI

I have try many sample in stack but still can`t get the idea which part i miss, the result in UI always display null, ..
here is the code i try :
class PointBallance {
String id, date, datetime, companyid, storecode, customercode, topup, amount, remark, cashier, invoice ;
PointBallance({this.id, this.date, this.datetime, this.companyid, this.storecode, this.customercode, this.topup, this.amount, this.remark, this.cashier, this.invoice});
factory PointBallance.fromJson(Map<String, dynamic> json) {
return PointBallance(
id: json['id'],
date: json['date'],
datetime: json['datetime'],
companyid: json['company_id'],
storecode: json['store_code'],
customercode: json['customer_code'],
topup: json['topup'],
amount: json['amount'],
remark: json['remark'],
cashier: json['cashier'],
invoice: json['invoice'],
);
}
}
the part for call http is here :
Future<List<PointBallance>> pointBal() async {
var url = 'http://someUrl';
var res = await http.get(url);
if(res.statusCode == 200) {
var dtpoint = json.decode(res.body);
print(dtpoint);
var bel = List<PointBallance>.from(dtpoint.map((i) => PointBallance.fromJson(i)));
return bel;
} else {
throw Exception(
"Request to $url failed with status ${res.statusCode}: ${res.body}"
);
}
}
and for screen to display data ..
class _PointScreenState extends State<PointScreen> {
Future<List<PointBallance>> _point;
AuthService _authService = new AuthService();
#override
void initState() {
_point = _authService.pointBal();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My Point'),
),
body: FutureBuilder<List<PointBallance>>(
future: _point,
builder: (context, snapshot) {
if (snapshot.hasData) {
var dt = snapshot.data[0].id;
return Column(
children: <Widget>[
**Text('in the top $dt'),**
Expanded(
child: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder:(BuildContext context, int index){
var hei = snapshot.data[index];
return **Text(hei.id != null ? hei.id : 'Cant get data')**;
}),
),
],
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return CircularProgressIndicator();
}),
);
}
}
in console i got result
print(dtpoint);
any guide to correctly display data result? because in console there is result.