How to Create a Select Dropdown with API in Flutter

How to Create a Select Dropdown with API in Flutter

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.

Our exercise this time is to create a select dropdown with data sourced from the API. Sometimes we need to fetch data dynamically from the internet to display in dropdown options, then it is quite important to learn.

We use api data from 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.

Membuat Dropdown Select API di Flutter
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:, ), 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('')); 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: 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:
    1. import 'package:flutter/material.dart';: Imports the Flutter material package, which provides user interface components and widgets.
    2. import 'package:http/http.dart' as http;: Imports the http package to perform HTTP requests.
    3. import 'dart:convert';: Imports the dart:convert library for managing JSON data.
    4. void main() { ... }: Flutter application entry point. Runs the MyApp widget.
    5. class MyApp extends StatelessWidget { ... }: Defines a Flutter widget named MyApp. It represents the root of the application and sets the initial theme and route.
    6. class MyForm extends StatefulWidget { ... }: Defines a MyForm stateful widget that extends StatefulWidget. It stores mutable state for the form.
    7. final GlobalKey<FormState> _formKey = GlobalKey<FormState>();: Creates a global key for the form widget. This key is used to identify and validate the form.
    8. Strings? selectedCategory;: Declares a nullable string variable to store the value of the selected category.
    9. List<String> categoryOptions = [];: Declares an empty list to store category options retrieved from the API.
    10. String result = '';: Declares an empty string variable to store the form submission results.
    11. 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.
    12. Future<void> fetchCategories() async { ... }: Defines the fetchCategories asynchronous method to retrieve category options from the API.
    13. var response = await http.get(Uri.parse(''));: Sends an HTTP GET request to the specified URL using the http package and waits for the response.
    14. if (response.statusCode == 200) { ... }: Checks whether the HTTP response was successful (status code 200).
    15. var data = jsonDecode(response.body);: Parses the response body from JSON format to a Dart object.
    16. setState(() { ... }): Updates the widget state with retrieved category options.
    17. void _submitForm() { ... }: Defines the _submitForm method that is called when the form is submitted.
    18. if (_formKey.currentState!.validate()) { ... }: Validates the form using the form key and checks whether all form fields are valid.
    19. _formKey.currentState!.save();: Saves the current form field value.
    20. setState(() { ... }): Updates the widget state with the selected category value.
    21. Widget build(BuildContext context) { ... }: Overrides the build method to build the widget hierarchy.
    22. DropdownButtonFormField<String>( ... ): Creates a dropdown button form field widget. This displays a dropdown list of category options.
    23. ElevatedButton( ... ): Creates a button widget for submitting the form.
    24. 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.

    Post a Comment