Flutter Dropdown from MySQL Database
In this example, we will add list of categories in DropdownButtonFormField() from MySQL database. We will get JSON data from MySQL Database using PHP API.
1.Database and Table Creation
Now, the first step is to create the database and the categories table inside the database.
Execute the following SQL queries to create the db_sample database and categories table inside your MySQL database.
CREATE DATABASE db_sample;
USE db_sample;
CREATE TABLE `categories` ( `category_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `category_name` varchar(45) NOT NULL DEFAULT '', PRIMARY KEY (`category_id`) );
2. Creating PHP API to get JSON data
- First, We have to create a
flutter_apifolder in yourwwworhtdocsdirectory. - Next, create a
get_all_categories.phpfile influtter_apifolder. - Put all the below code inside the
get_all_categories.phpfile.
get_all_categories.php
<?php $con=mysqli_connect("localhost","root","","db_sample"); $json = file_get_contents('php://input'); $data=[]; $sql="select * from categories"; $res=$con->query($sql); if($res->fetch_assoc()){ while($row=$res->fetch_assoc()){ $data[]=$row; } } echo json_encode($data); ?>
3. Coding For Flutter App
Create a class named as CategoryData. We would use this class to populate items from JSON data. We would create variable named as cid and cname which would hold and populate items from JSON data.
class CategoryData { String cid; String cname; CategoryData({this.cid, this.cname}); factory CategoryData.fromJson(Map<String, dynamic> json) { return new CategoryData( cid: json['category_id'], cname: json['category_name'], ); } }
Create a function named as getData. We would use this function get JSON data from server(PHP API).
//Get all categories from API Future<Null> getData() async { final response = await http.post("http://192.168.10.103/flutter_api/get_all_categories.php"); if (response.statusCode == 200) { if (response.body.isNotEmpty) { var jsonResult = jsonDecode(response.body); setState(() { for (Map user in jsonResult) { _categoryData.add(CategoryData.fromJson(user)); } }); } } }
Populate data to DropdownButtonFormField
DropdownButtonFormField( hint: Text("Select Category"), value: selectedCate, onChanged: (CategoryData value) { setState(() { selectedCate = value; }); }, items: _categoryData.map((CategoryData cate) => DropdownMenuItem<CategoryData>( child: Text(cate.cname), value: cate, )).toList(), ),
Complete Source code for main.dart:
main.dart
import 'package:flutter/material.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Dropdown Example', debugShowCheckedModeBanner: false, home: Example(), ); } } class Example extends StatefulWidget { @override State<Example> createState() => _ExamplePageState(); } class _ExamplePageState extends State<Example> { List<CategoryData> _categoryData = []; CategoryData selectedCate; //Get all categories from API Future<Null> getData() async { final response = await http .post("http://192.168.10.103/flutter_api/get_all_categories.php"); if (response.statusCode == 200) { if (response.body.isNotEmpty) { var jsonResult = jsonDecode(response.body); setState(() { for (Map user in jsonResult) { _categoryData.add(CategoryData.fromJson(user)); } }); } } } @override void initState() { super.initState(); getData(); } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( body: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.all(15.0), child: Form( child: DropdownButtonFormField( hint: Text("Select Category"), value: selectedCate, onChanged: (CategoryData value) { setState(() { selectedCate = value; }); }, items: _categoryData .map( (CategoryData cate) => DropdownMenuItem<CategoryData>( child: Text(cate.cname), value: cate, )) .toList(), ), ), ), ], ), ), ); } } class CategoryData { String cid; String cname; CategoryData({this.cid, this.cname}); factory CategoryData.fromJson(Map<String, dynamic> json) { return new CategoryData( cid: json['category_id'], cname: json['category_name'], ); } }
Output :