Good afternoon, I am making a call to my api to bring the businesses that I have registered.
This is my model
class Shops{
Shops({
this.id,
this.name,
this.phone,
this.merchantType,
this.address,
this.city,
this.distance,
this.logo,
});
String id;
String name;
String phone;
String merchantType;
String address;
String city;
double distance;
String logo;
factory Shops.fromJson(Map<String, dynamic> json){
return Shops(
id: json["_id"],
name : json["name"],
phone : json["phone"],
merchantType : json["merchantType"],
address : json["address"],
city : json["city"],
distance : json["distance"].toDouble(),
logo : json["logo"],
);
}
}
Here I make the call
Future<Shops> getShops(var userLatitude, var userLongitude) async {
final response =
await http.get('https://dry-plateau-30024.herokuapp.com/v1/front/merchants?lat=$userLatitude&lng=$userLongitude');
if (response.statusCode == 200) {
return Shops.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load Shops');
}
}
so I show the results
FutureBuilder<Shops>(
future:
getShops(services.userLatitude, services.userLongitude),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.name);
} else if (snapshot.hasError) {
return Information(
title: 'No results found',
subtitle: 'It seems there is nothing in your area',
img: 'assets/nada.png',
);
} else {
return CircularProgressIndicator();
}
},
)
This returns me the following error
_TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
I am evolving with the framework and the dart language, I am presented with these errors that perhaps for you are a newbie. I would appreciate a little help
Using the new link for the JSON you have given. Since it is a list we will have to cast it to a list and map through it. Before you were just returning one instance of ShopsFuture<Shops> instead of Future<List<Shops>>
class _CompaniesState extends State<Companies> {
Future<List<Shops>> getShops(var userLatitude, var userLongitude) async {
final response =
await http.get("https://dry-plateau-30024.herokuapp.com/v1/front/merchants?lat=-27.4885846&lng=-58.9509858");
if (response.statusCode == 200) {
// typecasting it into a list
var jsonData = json.decode(response.body) as List;
// Map through it and return it
return jsonData.map((shop) => Shops.fromJson(shop)).toList();
} else {
throw Exception('Failed to load Shops');
}
}
#override
Widget build(BuildContext context) {
return Container(
child: FutureBuilder<List<Shops>>(
future: getShops(12, 20),
builder: (context, snapshot) {
if (snapshot.hasData) {
// Accessing the first map from the list and getting the name key
return Text(snapshot.data[0].name);
} else if (snapshot.hasError) {
return null;
return Information(
title: 'No results found',
subtitle: 'It seems there is nothing in your area',
img: 'assets/nada.png',
);
} else {
return CircularProgressIndicator();
}
},
));
}
}
Related
I want to get data from API and convert it List to show it to Mobile, but FutureBuilder always said my data is null. I already print my data it has the data. But when I return it to FutureBuilder it just null.
API Example
{
"success": true,
"data": {
"current_page": 1,
"data": [
{
"absence_date": "2021-02-09",
"time_in": "07:51:34",
"time_out": "17:14:28"
},
{
"absence_date": "2021-02-08",
"time_in": "07:53:56",
"time_out": "17:09:15"
},
{
"absence_date": "2021-02-05",
"time_in": "07:53:32",
"time_out": "17:17:31"
}
],
"last_page": 4
}
}
Attendance.dart -> Model
#JsonSerializable()
class Attendance {
#JsonKey()
List<dynamic> data;
#JsonKey()
int last_page;
Attendance();
factory Attendance.fromJson(Map<String, dynamic> json) => _$AttendanceFromJson(json);
Map<String, dynamic> toJson() => _$AttendanceToJson(this);
}
ListView.dart -> _fecthJobs
Widget build(BuildContext context) {
return FutureBuilder<List<Job>>(
future: _fetchJobs(),
builder: (context, snapshot) {
print(snapshot.data);
if (snapshot.hasData) {
List<Job> data = snapshot.data;
return _jobsListView(data);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
);
}
Future<List<Job>> _fetchJobs() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var email = prefs.getString('email');
await api.attendances(email).then((items) async {
if (items.success == true) {
Attendance att = Attendance.fromJson(items.data);
print(att.data);
return att.data.map((job) => new Job.fromJson(job)).toList();
}
}).catchError((e) {
print('Exception $e');
});
}
I print att.data, it has the data API, but when it in snapshot.data it say it's null
I'm working on flutter project, in which I'm calling an POST API. Its response is like
{
"_id": "5f61a39b8b7cf93550898b63",
"buildname": "ANT PC DORYLUS RZ320G",
"processor": "AMD Ryzen 3 3200G (4Core, 4Threads, Upto 4.0 Ghz)",
"motherboard": "MSI B450M PRO m2 Max",
"ram": "8GB ADATA XPG Gammix D30 DDR4 3000MHz",
"graphiccard": "Radeon Vega Graphics",
"ssd": "120GB ADATA/Crucial SATA SSD",
"hdd": "1 TB WD Blue SATA HDD 7200 RPM",
"psu": "Antec VP450P IN",
"cpucooler": "AMD STOCK COOLER",
"os": "30 Days Microsoft Windows 10 Home 64-Bit Trial",
"cpucase": "Antec NX200",
"price": "28437.00",
"createdAt": "2020-09-16T05:33:15.383Z",
"__v": 0
}
I wrote this following code but it showing me an error type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'PreBuildResponse'
Code:
Future<List<PreBuildResponse>> _fetchProduct() async {
final url = 'http://10.0.2.2:3000/prebuild/product';
final response = await http.post(
url,
body: {
'id' : "$productId"
}
);
if (response.statusCode == 200) {
List jsonResponse = json.decode(response.body);
return jsonResponse
.map((list) => new PreBuildResponse.fromJson(list))
.toList();
} else {
throw Exception('Failed to load data from API');
}
}
#override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: SingleChildScrollView(
child: FutureBuilder(
future: _fetchProduct(),
builder: (context, snapshot) {
if (snapshot.hasData) {
PreBuildResponse data = snapshot.data;
return Text(data.buildname);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
),
)
);
}
}
And find the model code here https://gist.github.com/vaandhare/3aa46c71369f012514cfafe4911cd11c
Future<PreBuildResponse> _fetchProduct() async {
final url = 'http://10.0.2.2:3000/prebuild/product';
final response = await http.post(
url,
body: {
'id' : "$productId"
}
);
if (response.statusCode == 200) {
return PreBuildResponse.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load data from API');
}
}
you have to convert your JSON response to your model class.
there should have a fromJson method In the model class which you can use here while converting the JSON to your model class.
I have a Book Model class here so that you can refer it.
Future<List<Book>> getAllBook() async {
http.Response response = await http.get(
EndPoint.Book,
);
if (response.statusCode == 200) {
var parsed = jsonDecode(response.body);
var bookData = parsed['books'];
List<Book> data = bookData.map<Book>((e) => Book.fromJson(e)).toList();
print(data);
return data;
}
}
I am trying to make live score app ,I have a model created by quiqtype.io from json :
import 'dart:convert';
Live liveFromJson(String str) => Live.fromJson(json.decode(str));
String liveToJson(Live data) => json.encode(data.toJson());
class Live {
Live({
this.success,
this.data,
});
bool success;
Data data;
factory Live.fromJson(Map<String, dynamic> json) => Live(
success: json["success"],
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"success": success,
"data": data.toJson(),
};
}
class Data {
Data({
this.fixtures,
this.nextPage,
this.prevPage,
});
List<Fixture> fixtures;
String nextPage;
bool prevPage;
factory Data.fromJson(Map<String, dynamic> json) => Data(
fixtures: List<Fixture>.from(
json["fixtures"].map((x) => Fixture.fromJson(x))),
nextPage: json["next_page"],
prevPage: json["prev_page"],
);
Map<String, dynamic> toJson() => {
"fixtures": List<dynamic>.from(fixtures.map((x) => x.toJson())),
"next_page": nextPage,
"prev_page": prevPage,
};
}
class Fixture {
Fixture({
this.id,
this.date,
this.time,
this.round,
this.homeName,
this.awayName,
this.location,
this.leagueId,
this.competitionId,
this.homeId,
this.awayId,
this.competition,
this.league,
});
String id;
DateTime date;
String time;
String round;
String homeName;
String awayName;
String location;
String leagueId;
String competitionId;
String homeId;
String awayId;
Competition competition;
League league;
factory Fixture.fromJson(Map<String, dynamic> json) => Fixture(
id: json["id"],
date: DateTime.parse(json["date"]),
time: json["time"],
round: json["round"],
homeName: json["home_name"],
awayName: json["away_name"],
location: json["location"],
leagueId: json["league_id"],
competitionId: json["competition_id"],
homeId: json["home_id"],
awayId: json["away_id"],
competition: Competition.fromJson(json["competition"]),
league: json["league"] == null ? null : League.fromJson(json["league"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"date":
"${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}",
"time": time,
"round": round,
"home_name": homeName,
"away_name": awayName,
"location": location,
"league_id": leagueId,
"competition_id": competitionId,
"home_id": homeId,
"away_id": awayId,
"competition": competition.toJson(),
"league": league == null ? null : league.toJson(),
};
}
class Competition {
Competition({
this.id,
this.name,
});
String id;
String name;
factory Competition.fromJson(Map<String, dynamic> json) => Competition(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
class League {
League({
this.id,
this.name,
this.countryId,
});
String id;
String name;
String countryId;
factory League.fromJson(Map<String, dynamic> json) => League(
id: json["id"],
name: json["name"],
countryId: json["country_id"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"country_id": countryId,
};
}
the i create API service class :
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:myexpect/models/match_fixture.dart';
class Api {
Future<Live> get_fixture() async {
var fixture_model = null;
var client = http.Client();
try {
var url =
'https://livescore-api.com/api-client/fixtures/matches.json?key=xxxxxxC&secret=yyyyy&page=1';
var response = await client.get(url);
if (response.statusCode == 200) {
var jsonString = response.body;
var jsonMap = json.decode(jsonString);
fixture_model = Live.fromJson(jsonMap);
print(jsonMap ): //--- printed the list in console successfully
}
} catch (Exception) {
return fixture_model;
}
}
}
I am now trying to view this data's in future building in this page :
import 'package:flutter/material.dart';
import '../services/live_score_api.dart';
import '../models/match_fixture.dart';
class LiveScore extends StatefulWidget {
#override
_LiveScoreState createState() => _LiveScoreState();
}
class _LiveScoreState extends State<LiveScore> {
Future<Live> _fixtures;
#override
void initState() {
_fixtures = Api().get_fixture();
super.initState();
}
#override
Widget build(BuildContext context) {
return FutureBuilder<Live>(
future: _fixtures,
builder: (ctx, snapshot) {
if (snapshot.connectionState == ConnectionState.none ||
snapshot.connectionState == ConnectionState.waiting ||
snapshot.connectionState == ConnectionState.active ||
snapshot.data == null) {
return Container(
child: Text('Loading.......'),
);
} else {
return ListView.builder(
itemCount: snapshot.data.data.fixtures.length,
itemBuilder: (ctx, index) {
var data = snapshot.data.data.fixtures[index];
return Text(data.time);
});
}
},
);
}
}
when i load this page ,the list of data printed successfully at console but the future builder receive null ,therefore just the text 'Loading ...' is viewed ,and no error no exception found
You want to implement your future builder like this:
return FutureBuilder<Live>(
future: _fixtures,
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
case ConnectionState.active:
// Loading widget
return CircularProgressIndicator();
case ConnectionState.done:
if (snapshot.hasError) {
// return error widget
}
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.data.fixtures.length,
itemBuilder: (ctx, index) {
var data = snapshot.data.data.fixtures[index];
return Text(data.time);
});
}
}
},
);
On top of that, you catch the exception, but you don't throw an exception. So it will not throw an error. Which is kinda what you want to know in a future builder. I recommend throwing an exception.
I found my error ,is here :
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:myexpect/models/match_fixture.dart';
class Api {
Future<Live> get_fixture() async {
var fixture_model = null;
var client = http.Client();
try {
var url =
'https://livescore-api.com/api-client/fixtures/matches.json?key=xxxxxxC&secret=yyyyy&page=1';
var response = await client.get(url);
if (response.statusCode == 200) {
var jsonString = response.body;
var jsonMap = json.decode(jsonString);
fixture_model = Live.fromJson(jsonMap);
print(jsonMap ): //--- printed the list in console successfully
}
} catch (Exception) {
return fixture_model;
}
}
}
I forgot to return the list outside catch exception ,after i added return it is fixed :
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:myexpect/models/match_fixture.dart';
class Api {
Future<Live> get_fixture() async {
var fixture_model = null;
var client = http.Client();
try {
var url =
'https://livescore-api.com/api-client/fixtures/matches.json?key=xxxxxxC&secret=yyyyy&page=1';
var response = await client.get(url);
if (response.statusCode == 200) {
var jsonString = response.body;
var jsonMap = json.decode(jsonString);
fixture_model = Live.fromJson(jsonMap);
print(jsonMap ): //--- printed the list in console successfully
}
} catch (Exception) {
return fixture_model;
}
return fixture_model; //------------I added this line that i forgot :)
}
}
currently working on a flutter project with API. I'm quite new to flutter,
My Code:
Results null.
Being working on it for quite some time but couldn't find a solution. First, try on a flutter app therefore I'm quite new to this, would appreciate any solutions or tips/resources.
All variables are resulting in null as you can see I tried printing them couldn't figure out why.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
void main() => runApp(MyApp());
Future<Data> getData() async {
final response = await get("https://covid-api.com/api/reports?date=2020-03-25&iso=TUR®ion_name=Turkey");
if(response.statusCode == 200) {
return Data.fromJson(jsonDecode(response.body));
} else {
throw Exception('Not Working');
}
}
class Data {
String date;
int confirmed;
int deaths;
int recovered;
int confirmedDiff;
int deathsDiff;
int recoveredDiff;
int active;
int activeDiff;
double fatalityRate;
Data({
this.date,
this.confirmed,
this.deaths,
this.recovered,
this.confirmedDiff,
this.deathsDiff,
this.recoveredDiff,
this.active,
this.activeDiff,
this.fatalityRate,
});
factory Data.fromJson(Map<String, dynamic> json) {
return Data(
confirmed: json['confirmed'],
deaths: json['deaths'],
recovered: json['recovered'],
confirmedDiff: json['confirmed_diff'],
deathsDiff: json['deaths_diff'],
recoveredDiff: json['recovered_diff'],
active: json['active'],
activeDiff: json['active_diff'],
fatalityRate: json['fatality_rate'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['date'] = this.date;
data['confirmed'] = this.confirmed;
data['deaths'] = this.deaths;
data['recovered'] = this.recovered;
data['confirmed_diff'] = this.confirmedDiff;
data['deaths_diff'] = this.deathsDiff;
data['recovered_diff'] = this.recoveredDiff;
data['active'] = this.active;
data['active_diff'] = this.activeDiff;
data['fatality_rate'] = this.fatalityRate;
return data;
}
}
class MyApp extends StatelessWidget {
final Future<Data> data = getData();
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primaryColor: Colors.red),
home: Scaffold(
appBar: AppBar(title: Text('COVID-19 Turkey')),
body: Center(
child: FutureBuilder<Data>(
future: data,
builder: (context, snapshot) {
print(snapshot.data.deaths);
print('wtf');
print(snapshot.data.deathsDiff);
print(snapshot.data.recovered);
if(snapshot.hasData){
return Text(snapshot.data.confirmed.toString());
} else if (snapshot.hasError) {
return Text('Error');
}
return Center(child: CircularProgressIndicator(),);
},
),)
)
);
}
}
I think the following is the right way of using FutureBuilder:
FutureBuilder(
future: getData(),
builder: (context, snapshot) {
if (!snapshot.hasData
&& snapshot.connectionState != ConnectionState.done) {
return Center(child: CircularProgressIndicator());
}
if(snapshot.hasData) {
return Text(snapshot.data.confirmed.toString());
} else if (snapshot.hasError) {
return Text('Error');
}
});
Hope it helps!
The problem is in your JSON parsing. On this line,
return Data.fromJson(jsonDecode(response.body));
I called your API and it is giving a Map in which there is a data field and then there is a list of objects in it.
Your getData function needs to be like this,
Future<Data> getData() async {
final response = await get("https://covid-api.com/api/reports?date=2020-03-25&iso=TUR®ion_name=Turkey");
if(response.statusCode == 200) {
var data = jsonDecode(response.body);
var firstObj = (data['data'] as List<dynamic>).first;
return Data.fromJson(firstObj);
} else {
throw Exception('Not Working');
}
}
Hope this fixes it for you.
I'm new to Flutter and Dart, and I'm trying to write a application to test it.
I have an api that I'm getting the data for the app, and was trying to use the StatefulWidget and the FutureBuilder.
When I run the method to call the api I have the results (used print() to test it), but when I get the data from loadData method it retrives null.
So loadData prints the data, initState and FutureBuilder the data returns null. What am I missing here.
I have added the service and the models used for the request... hope it help.
Future<CoachesModelRes> loadData(Profile _profile) async {
await getPost(_profile.getToken()).then((response) {
if (response.statusCode == 200) {
CoachesModelRes coaches = coachesModel.postFromJson(response.body);
if (coaches.count > 0) {
print(coaches.count);
print(coaches.coaches[0].description);
return coaches;
} else {
return null;
}
} else {
String code = response.statusCode.toString();
return null;
}
}).catchError((error) {
print(error.toString());
return null;
});
}
#override
void initState() {
super.initState();
print(widget.profile.getToken());
data = loadData(widget.profile);
data.then((data_) async {
var cenas = data_.count;
print("asdasd $cenas");
});
}
Future<CoachesModelRes> data;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: appWhiteColor,
appBar: applicationBar(),
drawer: adminDrawer(widget.profile, AdminDrawerListEnum.coaches, context),
body: FutureBuilder<CoachesModelRes>(
future: data,
builder: (context, snapshot) {
//print(snapshot.data.count.toString());
if (snapshot.hasData) {
return Text("nop");
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Text("nop");
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
);
}
Future<http.Response> getPost(String token) async {
final response = await http.get(new Uri.http("$apiUrl", "$coachesEndPoint"),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.authorizationHeader : 'Bearer $token'
},
);
return response;
}
CoachesModelRes postFromJson(String str) => CoachesModelRes.fromJson(json.decode(str));
class CoachesModelRes {
int count;
List<CoachModelRes> coaches;
CoachesModelRes({
this.count,
this.coaches,
});
factory CoachesModelRes.fromJson(Map<String, dynamic> json) => new CoachesModelRes(
count: json["count"],
coaches: (json["coaches"] as List).map((i) => CoachModelRes.fromJson(i)).toList(),
);
}
CoachModelRes postFromJson(String str) => CoachModelRes.fromJson(json.decode(str));
class CoachModelRes {
String id;
String firstName;
String lastName;
String description;
String username;
String notes;
List<String> roles;
CoachModelRes({
this.id,
this.firstName,
this.lastName,
this.description,
this.username,
this.notes,
this.roles,
});
factory CoachModelRes.fromJson(Map<String, dynamic> json) => new CoachModelRes(
id: json["id"],
firstName: json["firstName"],
lastName: json["lastName"],
description: json["description"],
username: json["username"],
notes: json["notes"],
roles: new List<String>.from(json["roles"]),
);
}
Future<CoachesModelRes> loadData(Profile _profile) async {
final response = await getPost(_profile.getToken());
try{if (response.statusCode == 200) {
CoachesModelRes coaches = coachesModel.postFromJson(response.body);
if (coaches.count > 0) {
print(coaches.count);
print(coaches.coaches[0].description);
return coaches;
} else {
return null;
}
} else {
String code = response.statusCode.toString();
return null;
}}catch(e){
return null ;
}
}
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: appWhiteColor,
appBar: applicationBar(),
drawer: adminDrawer(widget.profile, AdminDrawerListEnum.coaches, context),
body: FutureBuilder<CoachesModelRes>(
future: loadData(widget.profile),
builder: (context, snapshot) {
//print(snapshot.data.count.toString());
if (snapshot.hasData) {
return Text("nop");
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Text("nop");
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
);
}
The issue here is that the return statement should be at the end of the method.
Because the getPost will return data to the loadData.
And when the getPost finishes the loadData will return data to the method that invoked him.
In my case, the loadData is not returning anything so the snapshot in the FutureBuilder it's always null.
It's logic that it is this way now, but at the time I could not figure it out :\
Future<CoachesModelRes> loadData(Profile _profile) async {
// So I need to create a variable to return
CoachesModelRes response;
//-----
await getPost(_profile.getToken()).then((response) {
if (response.statusCode == 200) {
CoachesModelRes coaches = coachesModel.postFromJson(response.body);
if (coaches.count > 0) {
print(coaches.count);
print(coaches.coaches[0].description);
// Set the variable value
response = coaches;
//-----
} else {
// Set the variable value
response = null;
//-----
}
} else {
String code = response.statusCode.toString();
// Set the variable value
response = null;
//-----
}
}).catchError((error) {
print(error.toString());
// Set the variable value
response = null;
//-----
});
// And at the end return the response variable
return response;
//-----
}