Reputation: 53
I want to get the names from the json plaeholder api in flutter. But it is giving error, the following is my code:
FutureBuilder(
future: getuser(),
builder: (context, snapshot){
if (snapshot.data==null) {
return Container(
child: Text("nothing"),
);
}
else return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context,i){
return ListTile(title: Text(snapshot.data[i].name),);
}
);
},
)
Upvotes: 1
Views: 973
Reputation: 14835
Try below code I think your Problem has been solved and also add id and email also
Your API Call Function
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(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
var name = snapshot.data[index]['name'];
var email = snapshot.data[index]['email'];
var id = snapshot.data[index]['id'];
return Card(
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.green.shade300),
borderRadius: BorderRadius.circular(15.0),
),
child: Column(
children: [
ListTile(
leading: Text(id.toString()),
title: Text(name),
subtitle: Text(email),
),
],
),
);
},
),
);
}
return CircularProgressIndicator();
},
),
),
Upvotes: 2