Creare una dropdown da FutureBuilder in Flutter
In questo articolo vediamo come creare una dropdown in Flutter usando FutureBuilder.
In sostanza i dati li prenderemo da una API in formato JSON.
Ovviamente prima dovete installare il package http.
Cominciamo dal nostro model:
import 'package:flutter/foundation.dart';
class Authors with ChangeNotifier {
List<Author> authors;
Authors({
required this.authors,
});
factory Authors.fromJson(Map<String, dynamic> json) => Authors(
authors:
List<Author>.from(json["authors"].map((x) => Author.fromJson(x))),
);
}
class Author with ChangeNotifier {
final int? id;
final String? name;
Author({
this.id,
this.name,
});
factory Author.fromJson(Map<String, dynamic> json) => Author(
id: json["id"],
name: json["name"],
);
}
Questo invece il nostro service:
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/author.dart';
class AuthorService {
Future<List<Author>> getAll() async {
final url = Uri.parse('https://www.mattepuffo.com/api/author/get.php');
final response = await http.get(url);
final Authors authors = Authors.fromJson(json.decode(response.body));
List<Author> items = authors.authors;
return items;
}
}
Come vedete il metodo getAll ritorna un Future.
A questo punto vediamo la nostra schermata:
import 'package:flutter/material.dart';
import '../models/author.dart';
import '../services/author_service.dart';
class FormAuthorScreen extends StatefulWidget {
const FormAuthorScreen({super.key});
static const routeName = '/form_author';
@override
State<FormAuthorScreen> createState() {
return _FormAuthorState();
}
}
class _FormAuthorState extends State<FormAuthorScreen> {
final _formKey = GlobalKey<FormState>();
final _authorService = AuthorService();
@override
void initState() {
super.initState();
}
@override
void dispose() {
super.dispose();
}
void _salva() {
_formKey.currentState!.validate();
_formKey.currentState!.save();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Aggiungi / modifica Libro"),
),
body: Padding(
padding: const EdgeInsets.all(12),
child: Form(
key: _formKey,
child: Column(
children: [
Center(
child: FutureBuilder<List<Author>>(
future: _authorService.getAll(),
builder: (context, initialData) {
if (initialData.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
if (initialData.hasError) {
return Center(
child: Text(
initialData.error.toString(),
),
);
}
if (initialData.data!.isEmpty) {
return const Center(
child: Text('Nessun elemento trovato!'),
);
}
List<String> items = [];
for (var e in initialData.data!) {
items.add(e.name!);
}
return DropdownButton<String>(
items: initialData.data!.map(
(item) {
return DropdownMenuItem<String>(
value: item.id.toString(),
child: Text(item.name!),
);
},
).toList(),
onChanged: (value) {
print(value);
},
);
},
),
),
],
),
),
),
);
}
}
Enjoy!
dart flutter futurebuilder dropdownbutton dropdownmenuitem
Commentami!