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,
Related
I try to get a List from this Api(https://www.getpostman.com/collections/fa1296508e65891de558)
But there does no appear any Object. Console showing => "E/LB (26008): fail to open file: No such file or directory
".
I tried to print respone.statusCode but the result does'n apper in console.
I hope to solve this problem, Thank you.
What can be the problem here?
My code:
class ApiSetting{
static const String _baseUri='http://demo-api.mr-dev.tech/api/';
static const String users= '${_baseUri}users';
}
**User Model
** class User {
late int id;
late String firstName;
late String lastName;
late String email;
late String mobile;
late String bio;
late String jobTitle;
late String latitude;
late String longitude;
late String country;
late String image;
late String active;
late String emailVerifiedAt;
late String imagesCount;
User.fromJson(Map<String, dynamic> json) {
id = json['id'];
firstName = json['first_name'];
lastName = json['last_name'];
email = json['email'];
mobile = json['mobile'];
bio = json['bio'];
jobTitle = json['job_title'];
latitude = json['latitude'];
longitude = json['longitude'];
country = json['country'];
image = json['image'];
active = json['active'];
emailVerifiedAt = json['email_verified_at'];
imagesCount = json['images_count'];
}
}
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:api_secand_project/api/api_setting.dart';
import 'package:api_secand_project/models/user.dart';
class UserApiController {
Future<List<User>> getUser() async {
var uri = Uri.parse(ApiSetting.users);
var response = await http.get(uri);
if (response.statusCode == 200) {
print(response.statusCode);
var jsonResponse = jsonDecode(response.body);
var userJsonArray = jsonResponse['data'] as List;
return userJsonArray
.map((jsonObject) => User.fromJson(jsonObject))
.toList();
}
return [];
}
}
import 'package:api_secand_project/api/controllers/user_api_controller.dart';
import 'package:api_secand_project/models/user.dart';
import 'package:flutter/material.dart';
class UsersScreen extends StatefulWidget {
const UsersScreen({Key? key}) : super(key: key);
#override
State<UsersScreen> createState() => _UsersScreenState();
}
class _UsersScreenState extends State<UsersScreen> {
List<User> _users=<User>[];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Users'),
),
body: FutureBuilder<List<User>>(
future: UserApiController().getUser(),
builder: (context, snapshot) {
if(snapshot.connectionState == ConnectionState.waiting){
return const Center(
child: CircularProgressIndicator(),
);
}
else if(snapshot.hasData){
_users=snapshot.data!;
return ListView.builder(
itemCount: _users.length,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
radius: 30,
// child: NetworkImage(snapshot.data!.),
),
title: Text(_users[index].firstName),
subtitle: Text(_users[index].mobile),
);
},
);
}
else{
return Center(child: Text('No Data',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 28),),);
}
},
));
}
}
The question was not very clear, and there is no clear screenshot or message from the error console,
It seems that you are using the BLOC pattern and since part of the code is missing, you decide to create one from scratch, maybe it will help you, I thought not to publish it, but maybe something from here will help you
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class GetApi extends StatefulWidget {
const GetApi({super.key});
#override
State<GetApi> createState() => _GetApiState();
}
class _GetApiState extends State<GetApi> {
List<User> users = [];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Get Api")),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ElevatedButton(
onPressed: () {
getApi();
},
child: const Text("Get Api"),
),
Flexible(
child: ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
User user = users[index];
return ListTile(
title: Text(user.name),
subtitle: Text(user.id),
);
}),
),
],
),
);
}
Future<void> getApi() async {
users = [];
Uri uri = Uri.parse("https://www.getpostman.com/collections/fa1296508e65891de558 ");
http.Response response = await http.get(uri);
if (response.statusCode == 200) {
//debugPrint("body: ${response.body}");
Map data = jsonDecode(response.body);
for (MapEntry item in data.entries) {
//debugPrint("key: ${item.key} value: ${item.value}");
if ("item" == item.key) {
List usersResponse = data["item"];
//debugPrint("users: ${users}");
for (dynamic json in usersResponse) {
User user = User.fromJson(json);
users.add(user);
//debugPrint("user: ${_user.name}");
}
}
}
if (!mounted) return;
setState(() {});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("succes -> status: ${response.statusCode}"),
backgroundColor: Colors.green,
),
);
} else {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("fail -> status: ${response.statusCode}"),
backgroundColor: Colors.red,
),
);
}
}
}
class User {
late String name;
late String id;
User.fromJson(Map<String, dynamic> json) {
name = json['name'];
id = json['id'];
}
}
Hello guys I face this problem when I Create a Search Delegate in a flutter
I try to call data from Firebase and add it in List Class but it shows me this error
List<dynamic> is not a subtype fo type List<Itemshop> of function result
Problem Here
List<ItemShop> ItemShopList = [];
CollectionReference ItemShopRef =
FirebaseFirestore.instance.collection('ItemShop');
List filterItemShop = [];
int counter = 0;
Future getData() async {
var responsce = await ItemShopRef.get();
responsce.docs.forEach((element) {
ItemShop itemShop = ItemShop(element["ItemCatgore"], element["ItemImage"],
element["ItemKG"], element['ItemName'], element["ItemPrice"]);
if (counter == 0) {
ItemShopList.add(itemShop);
}
});
print(ItemShopList);
return ItemShopList;
}
Class for ItemShop
class ItemShop {
final String ItemCatgore, ItemImage, ItemKG, ItemName;
int ItemPrice;
ItemShop(this.ItemCatgore, this.ItemImage, this.ItemKG, this.ItemName,
this.ItemPrice);
}
Full Code:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class SearchPage extends StatefulWidget {
const SearchPage({Key? key}) : super(key: key);
#override
State<SearchPage> createState() => _SearchPageState();
}
class _SearchPageState extends State<SearchPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color.fromARGB(255, 184, 132, 132),
actions: [
IconButton(
onPressed: () {
showSearch(context: context, delegate: mySearch());
},
icon: Icon(Icons.search))
],
),
);
}
}
class mySearch extends SearchDelegate {
List<ItemShop> ItemShopList = [];
CollectionReference ItemShopRef =
FirebaseFirestore.instance.collection('ItemShop');
List filterItemShop = [];
int counter = 0;
Future getData() async {
var responsce = await ItemShopRef.get();
responsce.docs.forEach((element) {
ItemShop itemShop = ItemShop(element["ItemCatgore"], element["ItemImage"],
element["ItemKG"], element['ItemName'], element["ItemPrice"]);
if (counter == 0) {
ItemShopList.add(itemShop);
}
});
print(ItemShopList);
return ItemShopList;
}
////////////////////////////////////////////////
#override
List<Widget>? buildActions(BuildContext context) {
return [
IconButton(
onPressed: () {
query = "";
},
icon: Icon(Icons.close))
];
}
#override
Widget? buildLeading(BuildContext context) {
return IconButton(
onPressed: () {
close(context, null);
},
icon: Icon(Icons.arrow_back));
}
#override
Widget buildResults(BuildContext context) {
return FutureBuilder(
future: getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int i) {
return snapshot.data[i].ItemName == query
? Card(
child: Column(
children: [
Container(
color: Colors.grey[200],
height: 150,
width: double.infinity,
child: Text(
snapshot.data[i].ItemName,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 35),
),
),
Container(
child: Text(snapshot.data[i].ItemName),
)
],
),
)
: Container();
});
}
});
}
#override
Widget buildSuggestions(BuildContext context) {
filterItemShop = ItemShopList.where((element) =>
element.ItemName.toLowerCase().contains(query.toLowerCase())).toList();
return FutureBuilder(
future: getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return ListView.builder(
itemCount:
query == "" ? snapshot.data.length : filterItemShop.length,
itemBuilder: (BuildContext context, int i) {
return InkWell(
onTap: () {
query = query == ""
? ItemShopList[i].ItemName
: filterItemShop[i].ItemName;
showResults(context);
},
child: Card(
child: query == ""
? ListTile(
leading: Text(snapshot.data[i].ItemName),
title: Text(snapshot.data[i].ItemName),
subtitle: Text(snapshot.data[i].ItemName),
)
: ListTile(
leading: Text(filterItemShop[i].ItemName),
title: Text(filterItemShop[i].ItemName),
subtitle: Text(filterItemShop[i].ItemName),
),
),
);
});
}
});
}
}
class ItemShop {
final String ItemCatgore, ItemImage, ItemKG, ItemName;
int ItemPrice;
ItemShop(this.ItemCatgore, this.ItemImage, this.ItemKG, this.ItemName,
this.ItemPrice);
}
there, I think the better approach is not for each but map. and use type defines variable so you will not get type error as long as you do not use casting method. final List<Itemshop> x = responsce.docs.map((e)=>Itemshop.fromMap(e.data()..docId = e.id)).toList(); return x;
ypu can also just retun the map fucntion like return responsce.docs.map((e)=> ....
Itemshop should be ItemShop, standard dart format.
Itemshop.fromMap is a function that you build in Itemshop class. data classes always have this kind of helper. fromMap, toMap, fromJson, toJson. a lot of code generation in the dart for this if you don't want to write it yourself.
For example for your comment,
import 'dart:convert';
class ItemShop {
final String? itemCatgore;
final String? itemImage;
final String? ItemKG;
final String? ItemName;
final String? ItemPrice;
ItemShop({
this.itemCatgore,
this.itemImage,
this.ItemKG,
this.ItemName,
this.ItemPrice,
});
Map<String, dynamic> toMap() {
return {
'itemCatgore': itemCatgore,
'itemImage': itemImage,
'ItemKG': ItemKG,
'ItemName': ItemName,
'ItemPrice': ItemPrice,
};
}
factory ItemShop.fromMap(Map<String, dynamic> map) {
return ItemShop(
itemCatgore: map['itemCatgore'],
itemImage: map['itemImage'],
ItemKG: map['ItemKG'],
ItemName: map['ItemName'],
ItemPrice: map['ItemPrice'],
);
}
String toJson() => json.encode(toMap());
factory ItemShop.fromJson(String source) =>
ItemShop.fromMap(json.decode(source));
ItemShop copyWith({
String? itemCatgore,
String? itemImage,
String? ItemKG,
String? ItemName,
String? ItemPrice,
}) {
return ItemShop(
itemCatgore: itemCatgore ?? this.itemCatgore,
itemImage: itemImage ?? this.itemImage,
ItemKG: ItemKG ?? this.ItemKG,
ItemName: ItemName ?? this.ItemName,
ItemPrice: ItemPrice ?? this.ItemPrice,
);
}
#override
String toString() {
return 'ItemShop(itemCatgore: $itemCatgore, itemImage: $itemImage, ItemKG: $ItemKG, ItemName: $ItemName, ItemPrice: $ItemPrice)';
}
#override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is ItemShop &&
other.itemCatgore == itemCatgore &&
other.itemImage == itemImage &&
other.ItemKG == ItemKG &&
other.ItemName == ItemName &&
other.ItemPrice == ItemPrice;
}
#override
int get hashCode {
return itemCatgore.hashCode ^
itemImage.hashCode ^
ItemKG.hashCode ^
ItemName.hashCode ^
ItemPrice.hashCode;
}
}
plus dart use camel case for all the variable and function (first latest is small later, second-word first letter is capital)
and all words first capital letter
Specify the type of future in futurebuilder, here it is list itemshop as shown below.
return FutureBuilder<List<ItemShop>>(
//TODO: YOUR CODE
);
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();
}
class Profile {
final List<String> photos;
final String name;
final int age;
final String education;
final String bio;
final int distance;
Profile({
this.photos,
this.name,
this.age,
this.education,
this.bio,
this.distance
});
}
class _MainControllerState extends State<MainController> {
static List<Profile> demoProfiles = fetchData();
static fetchData() async{
final db = await Firestore.instance;
List<Profile> list = [];
db.collection("users").getDocuments().then((querySnapshot){
querySnapshot.documents.forEach((document) {
list.add(Profile(
photos: document['photoUrl'],
name: document['photoUrl'],
age: document['photoUrl'],
distance: document['photoUrl'],
education: document['photoUrl']
));
});
});
return list;
}
final MatchEngine matchEngine = MatchEngine (
matches:demoProfiles.map((Profile profile) => Match(profile:
profile)).toList()
);
I am new to flutter.
when I run my code , I got the error :type 'Future' is not a subtype of type 'List .and if I change screen I will get the error:NoSuchMethodError: The method 'map' was called on null. How can I solve it ?
Thank you for helping me .
You need to specify the return type of method fetchData
static Future<List<Profile>> fetchData() async{
You need to convert you method to getData
Future<List<Data>> getData() async {
var response =
await http.get(Uri.https('jsonplaceholder.typicode.com', 'users'));
var jsonData = jsonDecode(response.body);
List<Data> dataList = [];
for (var u in jsonData) {
Data data = Data(u["name"], u["phone"], u["email"]);
dataList.add(data);
}
print(dataList.length);
return dataList;
}
And display in a Card
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Data Fetch"),
),
body: Container(
child: Card(
child: FutureBuilder<List<Data>>(
future: getData(),
builder: (context, snapshot) {
if (snapshot.data == null) {
return Container(
child: Text("Loading"),
);
}else{
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, i) {
return ListTile(
title: Column(
children: [
Text(snapshot.data![i].name),
Text(snapshot.data![i].phone),
Text(snapshot.data![i].email),
],
),
);
});
}
},
),
),
));
}
Its worked for me :) :) I hope this will help you.
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.