How To Populate Listview With Database In Flutter App

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

When in Mobile apps list view is crucial, in this article lets see how to build flutter list view using ListView widget and use it in our application, just for information sake Flutter is framework built by google to build multi platform application like Android, Web and IOS. Flutter follows Complete material design Specification. in this tutorial we shall create list view.

How To Populate Listview With Database In Flutter App

Populate Listview With Database
Step 1 
We cannot directly remove the time stamp from   Populate Listview With 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

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 Listview With Database In Flutter
main.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:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}

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

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() {
    return new MyHomePageState();
  }
}
class MyHomePageState extends State<MyHomePage> {
  DatabaseHelper db = DatabaseHelper();

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

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.black,
        title: Text('Fetching data from DB - ListView'),
      ),
      body: FutureBuilder<List<UserModel>>(
        future: db.getUserModelData(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) return Center(child: CircularProgressIndicator());

          return ListView(
            children: snapshot.data
                .map((user) => ListTile(
              title: Text(user.name),
              subtitle: Text(user.email),
              leading: CircleAvatar(
                backgroundColor: Colors.black,
                child: Text(user.name[0],
                    style: TextStyle(
                      fontSize: 18.0,
                      color: Colors.white,
                    )),
              ),
            ))
                .toList(),
          );
        },
      ),
    );
  }
}

 

Related Post