How To Populate Dropdownbutton Using Sqlite Database In Flutter

admin_img Posted By Bajarangi soft , Posted On 27-11-2020

In this article I will be demonstrating how to Populate data in Dropdown list (Spinner in android) from SQFlite Database in flutter. Inorder to do it, Please make sure to have a basic understanding of the stateless widgets and stateful widgets as we are dealing with the state of the data.

How To Populate Dropdownbutton Using Sqlite Database In Flutter

Populate Dropdownbutton Using Sqlite Database

Step 1 
We cannot directly remove the time stamp from Populate Dropdownbutton Using Sqlite Database but using the intl.dart package we can easily filter the date stamp from time stamp. So open your flutter project’s pubspec.yaml in code .

dependencies:
  flutter:
    sdk: flutter
  path: ^1.7.0
  path_provider: ^1.6.24
  sqflite: ^1.3.2+1
  http: ^0.12.2

Step 2
After done saving the pubspec.yaml file, Open your flutter project root folder in Command Prompt or Terminal and execute flutter pub get command.

flutter pub get



Complete Code For Populate Dropdownbutton Using Sqlite Database In Flutter
main.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io' as io;
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}
class MyHomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  DatabaseHelper db = DatabaseHelper();

  //Add data to db
  _saveData() async {
    UserModel user1 = UserModel(
      "Jone",
      "Jone Jonathan",
      "Jone@gmail.com",
      "Jonpass",
    );

    UserModel user2 = UserModel(
      "Jony",
      "BajarangiSoft.com",
      "info@BajarangiSoft.com",
      "Jony",
    );
    await db.saveData(user1);
    await db.saveData(user2);
  }

  @override
  void initState() {
    super.initState();
    _saveData();
  }

  UserModel _currentUser;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.indigo,
        title: Text('Fetching Data From Sqlite Db - Dropdownbutton'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            FutureBuilder<List<UserModel>>(
                future: db.getUserModelData(),
                builder: (BuildContext context,
                    AsyncSnapshot<List<UserModel>> snapshot) {
                  if (!snapshot.hasData) return CircularProgressIndicator();
                  return DropdownButton<UserModel>(
                    items: snapshot.data
                        .map((user) => DropdownMenuItem<UserModel>(
                      child: Text(user.name),
                      value: user,
                    ))
                        .toList(),
                    onChanged: (UserModel value) {
                      setState(() {
                        _currentUser = value;
                      });
                    },
                    isExpanded: false,
                    //value: _currentUser,
                    hint: Text('Select User'),
                  );
                }),
            SizedBox(height: 20.0),
            _currentUser != null
                ? Text(
              "Name: " +
                  _currentUser.name +
                  "\n Email: " +
                  _currentUser.email +
                  "\n Username: " +
                  _currentUser.username +
                  "\n Password: " +
                  _currentUser.password,
            )
                : Text("No User selected"),
          ],
        ),
      ),
    );
  }
}


class UserModel {
  String username;
  String name;
  String email;
  String password;

  UserModel(
      this.username,
      this.name,
      this.email,
      this.password,
      );

  UserModel.fromMap(dynamic obj) {
    this.name = obj["name"];
    this.username = obj["username"];
    this.email = obj["email"];
    this.password = obj["password"];
  }

  Map<String, dynamic> toMap() {
    var map = new Map<String, dynamic>();

    map["username"] = username;
    map["name"] = name;
    map["email"] = email;
    map["password"] = password;

    return map;
  }

  //Getters
  String get getName => name;
  String get getUsername => username;
  String get getPassword => password;
  String get getEmail => email;
}

class DatabaseHelper {
  static final DatabaseHelper _instance = new DatabaseHelper.internal();
  factory DatabaseHelper() => _instance;

  static Database _db;

  Future<Database> get db async {
    if (_db != null) return _db;
    _db = await initDb();
    return _db;
  }

  DatabaseHelper.internal();

  initDb() async {
    io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "main.db");
    var theDb = await openDatabase(path, version: 1, onCreate: _onCreate);
    return theDb;
  }

  void _onCreate(Database db, int version) async {
    await db.execute("""CREATE TABLE user(
        id INTEGER PRIMARY KEY,
        username TEXT,
        email TEXT,
        name TEXT,
        password TEXT
        )""");
  }

  Future<int> saveData(UserModel user) async {
    var dbClient = await db;
    int res = await dbClient.insert("user", user.toMap());
    return res;
  }

  Future<List<UserModel>> getUserModelData() async {
    var dbClient = await db;
    String sql;
    sql = "SELECT * FROM user";

    var result = await dbClient.rawQuery(sql);
    if (result.length == 0) return null;

    List<UserModel> list = result.map((item) {
      return UserModel.fromMap(item);
    }).toList();

    print(result);
    return list;
  }
}

Related Post