How to Populate DropDownButton using SQLite Database in Flutter

In this Google flutter code example we are going to learn how to populate dropdownbutton using Sqlite database in flutter.

The code is based on flutter version 1.0.0

Main.dart (App entry point)

import 'package:flutter/material.dart';
import 'week2/dropdownbutton_sqlite.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      //home: MyHomePage(title: 'Flutter Demo Home Page'),
      home: SqliteDropdown(),
    );
  }
}

dropdownbutton_sqlite.dart

import 'dart:convert';
import 'package:food_store/db_helper.dart';
import 'package:food_store/user_model.dart';
import 'package:http/http.dart' as http;

import 'package:flutter/material.dart';

class SqliteDropdown extends StatefulWidget {
  @override
  SqliteDropdownState createState() {
    return new SqliteDropdownState();
  }
}

class SqliteDropdownState extends State<SqliteDropdown> {
  DatabaseHelper db = DatabaseHelper();

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

    UserModel user2 = UserModel(
      "induce",
      "Inducesmile.com",
      "info@inducesmile.com",
      "induce",
    );
    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(
        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"),
          ],
        ),
      ),
    );
  }
}

user_model.dart

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;
}

db_helper.dart

import 'dart:async';
import 'dart:io' as io;

import './user_model.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';

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;
  }
}

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.