Hello everyone, welcome back at porkaone. On this occasion we will learn how to create a select dropdown in Flutter with API data quickly and easily. Are you curious? Come on, follow the tutorial below.
We use api data from https://dummyjson.com/products/categories. Later it will
be displayed in the dropdown options. The contents are product categories.
Please scroll down to see the final results
Read Another Article ✨ |
📰 1. How to Display a Website in Flutter with Webview read more |
📰 2. How to Make a Bubble Bottom Bar in Flutter read more |
📰 3. How to Install Java Development Kit and Add Variable Path to
ENV read more |
📰 4. How to Make Copy Feature in Flutter Apps read more |
How to Create a Select Dropdown with Data API in Flutter
1. Create a new flutter project with a free name. Use the latest version
of flutter or flutter that supports null safety.
2. Open pubspec.yaml. Then add http: package as shown below.
|
Add Package |
3. Open lib/main.dart then replace it with the script below.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Form Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyForm(),
);
}
}
class MyForm extends StatefulWidget {
@override
_MyFormState createState() => _MyFormState();
}
class _MyFormState extends State<MyForm> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
String? selectedCategory;
List<String> categoryOptions = [];
String result = '';
@override
void initState() {
super.initState();
fetchCategories();
}
Future<void> fetchCategories() async {
try {
var response = await http.get(Uri.parse('https://dummyjson.com/products/categories'));
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
setState(() {
categoryOptions = List<String>.from(data);
});
} else {
print('Failed to fetch categories: ${response.statusCode}');
}
} catch (error) {
print('Error fetching categories: $error');
}
}
void _submitForm() {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
setState(() {
result = 'Selected Category: $selectedCategory';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Form Example'),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
DropdownButtonFormField<String>(
decoration: const InputDecoration(
labelText: 'Category',
),
value: selectedCategory,
items: categoryOptions.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (newValue) {
setState(() {
selectedCategory = newValue;
});
},
),
const SizedBox(height: 20.0),
ElevatedButton(
onPressed: _submitForm,
child: const Text('Submit'),
),
const SizedBox(height: 20.0),
Text(
result,
style: const TextStyle(fontSize: 18.0),
),
],
),
),
),
);
}
}
Explanation of the script above:
- import 'package:flutter/material.dart';: Imports the Flutter material package, which provides user interface components and widgets.
- import 'package:http/http.dart' as http;: Imports the http package to perform HTTP requests.
- import 'dart:convert';: Imports the dart:convert library for managing JSON data.
- void main() { ... }: Flutter application entry point. Runs the MyApp widget.
- class MyApp extends StatelessWidget { ... }: Defines a Flutter widget named MyApp. It represents the root of the application and sets the initial theme and route.
- class MyForm extends StatefulWidget { ... }: Defines a MyForm stateful widget that extends StatefulWidget. It stores mutable state for the form.
- final GlobalKey<FormState> _formKey = GlobalKey<FormState>();: Creates a global key for the form widget. This key is used to identify and validate the form.
- Strings? selectedCategory;: Declares a nullable string variable to store the value of the selected category.
- List<String> categoryOptions = [];: Declares an empty list to store category options retrieved from the API.
- String result = '';: Declares an empty string variable to store the form submission results.
- void initState() { ... }: Overrides the initState method. This is a lifecycle method that is called when a widget is inserted into the tree. This method calls the fetchCategories method to retrieve category options.
- Future<void> fetchCategories() async { ... }: Defines the fetchCategories asynchronous method to retrieve category options from the API.
- var response = await http.get(Uri.parse('https://dummyjson.com/products/categories'));: Sends an HTTP GET request to the specified URL using the http package and waits for the response.
- if (response.statusCode == 200) { ... }: Checks whether the HTTP response was successful (status code 200).
- var data = jsonDecode(response.body);: Parses the response body from JSON format to a Dart object.
- setState(() { ... }): Updates the widget state with retrieved category options.
- void _submitForm() { ... }: Defines the _submitForm method that is called when the form is submitted.
- if (_formKey.currentState!.validate()) { ... }: Validates the form using the form key and checks whether all form fields are valid.
- _formKey.currentState!.save();: Saves the current form field value.
- setState(() { ... }): Updates the widget state with the selected category value.
- Widget build(BuildContext context) { ... }: Overrides the build method to build the widget hierarchy.
- DropdownButtonFormField<String>( ... ): Creates a dropdown button form field widget. This displays a dropdown list of category options.
- ElevatedButton( ... ): Creates a button widget for submitting the form.
- Text( ... ): Displays the results of the form submission.
Ok now run the emulator. If successful, the display will look like the image below.
That's it for this tutorial on how to create a select dropdown with API data in Flutter. Hopefully this short article helps. If you have any questions, please ask directly in the comments column below. That's all and receive a salary.
0 Comments
Come on ask us and let's discuss together
Emoji