I need to display data from an API get request in a dropdown, and when selecting a item from the drop down menu I need to save the id of the selected item into a variable.
Here is the URL "https://reqres.in/api/users?page=1
".
I have checked other posts already, but seems like the syntax changed a lot.
I am new to flutter.
From the above URL, I need the "data" array saved into a list.
CodePudding user response:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class User {
final int id;
final String email;
final String firstName;
final String lastName;
final String avatar;
const User({
required this.id,
required this.email,
required this.firstName,
required this.lastName,
required this.avatar,
});
User.fromJson(Map<String, dynamic> json)
: id = json['id'],
email = json['email'],
firstName = json['first_name'],
lastName = json['last_name'],
avatar = json['avatar'];
}
class UsersResponse {
final int page;
final int perPage;
final int total;
final int totalPages;
final List<User> data;
const UsersResponse({
required this.page,
required this.perPage,
required this.total,
required this.totalPages,
required this.data,
});
UsersResponse.fromJson(Map<String, dynamic> json)
: page = json['page'],
perPage = json['per_page'],
total = json['total'],
totalPages = json['total_pages'],
data = (json['data'] as List<dynamic>)
.map((json) => User.fromJson(json))
.toList();
}
class _MyHomePageState extends State<MyHomePage> {
late Future<List<User>> future;
User? selectedUser;
@override
void initState() {
super.initState();
future = _getUsers();
}
Future<List<User>> _getUsers() async {
final response =
await http.get(Uri.parse('https://reqres.in/api/users?page=1'));
Map<String, dynamic> json = jsonDecode(response.body);
final usersResponse = UsersResponse.fromJson(json);
return usersResponse.data;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder<List<User>>(
future: future,
builder: (context, snapshot) {
if (snapshot.hasError) {
// TODO: Proper error handling
return Text('Error: ${snapshot.error}');
}
if (snapshot.data == null) {
return const CircularProgressIndicator();
}
return Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
const Text(
'Select user:',
),
SizedBox(
height: 64,
child: DropdownButton<User>(
onChanged: (user) => setState(() => selectedUser = user),
value: selectedUser,
items: [
...snapshot.data!.map(
(user) => DropdownMenuItem(
value: user,
child: Row(
children: [
Image.network(user.avatar),
Text('${user.firstName} ${user.lastName}'),
],
),
),
)
],
),
),
],
),
);
}),
),
);
}
}
JSON response from https://reqres.in/api/users?page=1
{
"page": 1,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 1,
"email": "[email protected]",
"first_name": "George",
"last_name": "Bluth",
"avatar": "https://reqres.in/img/faces/1-image.jpg"
},
{
"id": 2,
"email": "[email protected]",
"first_name": "Janet",
"last_name": "Weaver",
"avatar": "https://reqres.in/img/faces/2-image.jpg"
},
{
"id": 3,
"email": "[email protected]",
"first_name": "Emma",
"last_name": "Wong",
"avatar": "https://reqres.in/img/faces/3-image.jpg"
},
{
"id": 4,
"email": "[email protected]",
"first_name": "Eve",
"last_name": "Holt",
"avatar": "https://reqres.in/img/faces/4-image.jpg"
},
{
"id": 5,
"email": "[email protected]",
"first_name": "Charles",
"last_name": "Morris",
"avatar": "https://reqres.in/img/faces/5-image.jpg"
},
{
"id": 6,
"email": "[email protected]",
"first_name": "Tracey",
"last_name": "Ramos",
"avatar": "https://reqres.in/img/faces/6-image.jpg"
}
],
"support": {
"url": "https://reqres.in/#support-heading",
"text": "To keep ReqRes free, contributions towards server costs are appreciated!"
}
}