Hello developers, today I have selected a very important topic in flutter app development,
The topic is –
- How to show data from Sqflite a dropdown in a flutter.
- Drop Down with sqlite in a flutter.
- Populating dropdown list in a database with flutter.
- Dropdown dependency in a flutter.
- Fetch and show data in the dropdown.
- Change the drop-down value based on the parent dropdown in a flutter.
Dropdown List in a flutter
In this article, we will look into how to make a Drop-down Search and binding items in a database table with API implementation have used the HTTP framework to achieve this result of the API and data binding a dropdown and search the result of the given enter value on the search box in flutter and using the dart programming.
Have used this article in some facts.
- I used dropdown dependency in a flutter.
- Create a database file in the flutter app.
- Create a table structure in Sqflite.
- Create a list of all data in Sqflite.
- Searching data in the dropdown.
- Bind the dropdown list in a flutter and the child dropdown list bind based on the parent dropdown.
- REST API implementation.
- Model class API responses structure.
- Country list dropdown in a flutter.
- State list dropdown in a flutter.
- Offline data use in a flutter.
Video dropdown list in the flutter
developers do not need the hitting API again and again, This data is used offline no need for the internet only one-time hitting API.
important library
Environment
- 1.71.0 (Universal)
- Dart Programming
- Flutter 3.0.5+ Version
- Build iOS
- Build Android
- Run iPhone 11 Pro
- Android SDK
- XCODE
- Terminal (on Mac/Linux) or CMD (on Windows)
- IDE (Android Studio/IntelliJ/Visual Studio Code)
Features structure
- Simple structure
- Navigation parent dropdown to fill child dropdown each other
- Search data in the Dropdown covers
- Scrolling with all data in the dropdown screen
Pods(Pub.dev)
- path_provider: ^2.0.8
- http: ^0.13.0
- shared_preferences: ^2.0.7
- fluttertoast: ^8.0.8
- flutter_spinkit: ^5.1.0
- intl_utils: ^2.7.0
- package_info: ^2.0.0
- permission_handler: ^6.0.1+1
- google_fonts: ^2.1.0
- sqflite: ^2.0.2
- dropdown_search2: ^1.0.2
Sqflite/Sqllite database class
import 'dart:io';
import 'package:path/path.dart';
import 'dart:async';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import '../module/marketPlace/location.dart';
class DBProvider {
static Database? _database;
static final DBProvider db = DBProvider._();
static int get _version => 1;
DBProvider._();
Future<Database?> get database async {
// If database exists, return database
if (_database != null) return _database;
// If database don't exists, create one
_database = await initDB();
return _database;
}
// Create the database and the wrms table
initDB() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
final path = join(documentsDirectory.path, 'LocationDB.db');
print(path);
return await openDatabase(path, version: _version, onOpen: (db) {},
onCreate: (Database db, int version) async {
await db.execute('CREATE TABLE LocationInfo('
'stateName TEXT,'
'stateId INTEGER,'
'cityName TEXT,'
'cityId INTEGER'
')');
//===2nd table
});
}
Future<void> insertLocation(LocationInfo location) async {
final db = await database;
await db!.insert(
'LocationInfo',
location.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
//===========end of the code in add local
Future<int> deleteAllLogin() async {
final db = await database;
final res = await db!.rawDelete('DELETE FROM LoginInfo');
print("delete all data in LoginInfo Table ");
return res;
}
Future<List<LocationInfo>> getUserLocation() async {
final db = await database;
final res = await db!.rawQuery("SELECT * FROM LocationInfo");
print(res);
List<LocationInfo> list =
res.isNotEmpty ? res.map((c) => LocationInfo.fromJson(c)).toList() : [];
return list;
}
Future<int> deleteSUserLocation() async {
final db = await database;
final res = await db!.rawDelete('DELETE FROM LocationInfo');
print("delete all data in LocationInfo Table ");
return res;
}
}
Create a database in the flutter project, add, edit, delete, and list the data of the array in flutter.
Model class database responses (country class responses)
//-- class name and parameters changes according to your needs this is demo responses class model
class LocationInfo {
final String? stateName;
final String? cityName;
final int? stateId;
final int? cityId;
LocationInfo(this.stateName, this.cityName, this.stateId, this.cityId);
factory LocationInfo.fromJson(Map<String, dynamic> json) {
// ignore: unnecessary_new
return new LocationInfo(
json["stateName"],
json["cityName"],
json["stateId"],
json["cityId"]
);
}
Map<String, dynamic> toJson() => {
"stateName": stateName,
"cityName": cityName,
"stateId": stateId,
"cityId":cityId,
};
Map<String, dynamic> toMap() {
return {
'stateName': stateName,
'cityName': cityName,
'stateId': stateId,
'cityId':cityId,
};
}
}
DropDownList – design, and code
List<LocationArray> _StateMasterList = [];
List<String> cityType = ['Please select city'];
List<String> stateType = [];
Padding(
padding: EdgeInsets.only(left: 16, right: 16, top: 10),
child:
DropdownSearch<String>(
mode: Mode.MENU,
showSelectedItems: true,
showSearchBox: true,
label: 'State',
hint: 'State'.tr,
popupItemDisabled: (String s) => s.startsWith('I'),
items: stateTypeI,
validator: (value) {
if (value == null) {
return 'State'.tr;
}
},
onChanged: (val)
{
setState(() async {
_currentStateType = val!;
cityType.clear();
cityType = ['Please select city'];
_currentCityType = cityType[0];
getCitys();
});
getCitys();//
// enter your logic to handle the city data
}
),
),
State and city dropdown design
import 'package:dairypartners/src/module/marketPlace/location.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:dropdown_search2/dropdown_search2.dart';
import '../../database/database.dart';
import '../../module/marketPlace/city_master.dart';
import '../../module/marketPlace/state_master.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
class ChooseLocationPage extends StatefulWidget {
@override
_ChooseLocationPageState createState() => _ChooseLocationPageState();
}
class _ChooseLocationPageState extends State<ChooseLocationPage> {
final GlobalKey<FormState> formKeyValidateUpdateLocationScreen =
GlobalKey<FormState>();
List<String> stateType = [];
List<String> stateTypeI = [];
List<String> cityType = ['Please select city'];
List<String> cityTypeI = [];
List<StateList> _stateMasterList = [];
List<CityList> _cityMasterList = [];
String? _currentStateType;
String? _currentCityType;
String? _stateID;
String? _cityID = '';
final db = DBProvider.db;
@override
void initState() {
if (!mounted) return;
getSateData();
super.initState();
}
String currentCountry = '';
Future<void> getSateData() async {
_sateMasterList = await db.getUserLocation();
for (int i = 0; i < _sateMasterList.length; i++) {
stateType.add(_sateMasterList[i].stateName!);
setState(() {
});
}
}
Future<String> _getStateID(String stateType) async {
var _filterFilter =
_stateMasterList.where((prod) => prod.level1 == stateType).toList();
print(_filterFilter);
for (int i = 0; i < _filterFilter.length; i++) {
_stateID = _filterFilter[i].level1Id.toString();
}
setState(() {
_stateID = _stateID;
});
return _stateID!;
}
Future<String> _getCityID(String cityType) async {
var _filterFilter =
_cityMasterList.where((prod) => prod.level2 == cityType).toList();
print(_filterFilter);
for (int i = 0; i < _filterFilter.length; i++) {
_cityID = _filterFilter[i].level2Id.toString();
}
setState(() {
if (_cityID == null) {
_cityID = '0';
} else {
_cityID = _cityID;
}
});
return _cityID!;
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: AppTheme.mainColor,
iconTheme: const IconThemeData(
color: Colors.white,
),
title: Text(
'your Location',
style: TextStyle(color: Colors.white),
),
elevation: 0, systemOverlayStyle: SystemUiOverlayStyle.dark,
),
body: Container(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 13, vertical: 10),
child: Form(
key: formKeyValidateUpdateLocationScreen,
child: Padding(
padding: const EdgeInsets.only(top: 7.0, left: 24.0, right: 24.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 16, right: 16, top: 10),
child:
DropdownSearch<String>(
mode: Mode.MENU,
showSelectedItems: true,
showSearchBox: true,
label: 'State'.tr,
hint: 'State'.tr,
popupItemDisabled: (String s) => s.startsWith('I'),
items: stateTypeI,
validator: (value) {
if (value == null) {
return 'State required'.tr;
}
},
onChanged: (val)
{
setState(() async {
_currentStateType = val!;
cityType.clear();
cityType = ['Please select city'];
_currentCityType = cityType[0];
getCitys();
});
getCitys();
}
),
),
const SizedBox(
height: 10,
),
Padding(
padding: EdgeInsets.only(left: 16, right: 16, top: 10),
child:
DropdownSearch<String>(
mode: Mode.MENU,
showSelectedItems: true,
showSearchBox: true,
label: 'City'.tr,
hint: 'City'.tr,
popupItemDisabled: (String s) => s.startsWith('I'),
items: cityType,
validator: (value) {
if (value == null) {
return 'City'.tr;
}
},
onChanged: (val) //=>
{
setState(() async {
_currentCityType = val!;
});
}
),
),
const SizedBox(
height: 10,
),
],
),
),
),
),
),
bottomNavigationBar: Container(
height: 65,
padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
decoration: const BoxDecoration(
color: Color.fromARGB(255, 234, 231, 231),
),
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: AppTheme.mainColor,
textStyle: CustomTextStyle.textFormFieldMedium
.copyWith(fontSize: 15, fontWeight: FontWeight.normal)),
onPressed: () async {
//-your code
}
},
child: Text('Next'),
),
),
);
}
}
State data get the DB in sqlfilte
//-state data get the db in sqlfilte
Future<void> getSateData() async {
_sateMasterList = await db.getUserLocation();
for (int i = 0; i < _sateMasterList.length; i++) {
stateType.add(_sateMasterList[i].stateName!);
setState(() {
});
}
}
final output
I hope it was a useful article, please share and subscribe to my channel, Thanks for reading and if you have any questions or comments, See you soon.