hello i'm working on an app with flutter and i have an error with Futurebuilder i dont understand please help
i trying to get title and desc depending of id with a future builder
this is my json
{"title":"15%GANT","desc":"donne 15 % sur les gants"}
This is my Future
Future<Data> fetchData(int id, String type) async {
var queryParameters = {
'type': type,
'id': id,
};
String url = 'tartapain.bzh';
var uri = Uri.https(url, '/api/scan/get.php', queryParameters);
final response = await http.get(uri);
if (response.statusCode == 200) {
if (response.body != null) {
return Data.fromJson(json.decode(response.body));
}
} else {
throw Exception('Failed to load the post');
}
}
this is my data class
class Data {
final String title;
final String desc;
Data({
this.title,
this.desc,
});
factory Data.fromJson(Map<String, dynamic> json) {
print(json['desc'] + " " + json['title'] + "\n");
return Data(
desc: json['desc'],
title: json['title'],
);
}
}
this is mt init
Future<Data> futureData;
@override
void initState() {
super.initState();
futureData = fetchData(widget.id, 'get_info_id');
}
And this is my futureBuilder
FutureBuilder(
future: futureData,
initialData: [],
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: Text("Loading..."));
}
if (snapshot.hasData) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
snapshot.data.title,
style: TextStyle(color: Colors.white, fontSize: 18),
),
Text(
snapshot.data.desc,
style: TextStyle(color: Colors.white, fontSize: 12),
)
],
);
} else if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.white, fontSize: 12),
);
} else {
return CircularProgressIndicator(
valueColor:
new AlwaysStoppedAnimation<Color>(Colors.black));
}
})
And i get this error :
type 'int' is not a subtype of type 'Iterable'
It seems like the error was caused by the ID which should be of type String. That solves the issue.
Than I suggest to implement some check in your model in case the values are empty.
class Data {
final String title;
final String desc;
Data({
this.title,
this.desc,
});
factory Data.fromJson(Map<String, dynamic> json) {
//print(json['desc'] + " " + json['title'] + "\n");
return Data(
desc: (json['desc']!=null)?json['desc']:'no desc',
title: (json['title']!=null)?json['title']:'no title',
);
}
}