3

I'm working on a Flutter project and using Sqflite database. I've managed to save data in db. Now I am trying to get list of all records from database based on table name and display them in "ListView.builder".

database_helper.dart

Future<List> getAllRecords(String dbTable) async {
    var dbClient = await db;
    var result = await dbClient.rawQuery("SELECT * FROM $dbTable");

    return result.toList();
}

employees_list.dart

import 'package:flutter/material.dart';
import 'package:flutter_with_db_single_helper/helpers/database_helper.dart';

var db = new DatabaseHelper();
Future<List> _users = db.getAllRecords("tabEmployee"); // CALLS FUTURE

class EmployeesListScreen extends StatefulWidget {
  @override
  _EmployeesListScreenState createState() => _EmployeesListScreenState();
}

class _EmployeesListScreenState extends State<EmployeesListScreen> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('List Of Employees'),
      ),
      body: ListView.builder(
        // itemCount: _users.length,
        itemBuilder: (_, int position) {
          return Card(
            child: ListTile(
              title:
                  Text("Employee Name: "), // EMPLOYEE NAME TO BE DISPLAYED HERE
            ),
          );
        },
      ),
    );
  }
}

Where did I go wrong? What can I do to display all my db table records in list?

1
  • 2
    what's the error? Commented Dec 5, 2018 at 14:13

2 Answers 2

11

You could use a FutureBuilder to get and display your data :

        class _EmployeesListScreenState extends State<EmployeesListScreen> {
          var db = new DatabaseHelper(); // CALLS FUTURE

          @override
          Widget build(BuildContext context) {
            return Scaffold(
              appBar: AppBar(
                title: Text('List Of Employees'),
              ),
              body: FutureBuilder<List>(
                future: db.getAllRecords("tabEmployee"),
                initialData: List(),
                builder: (context, snapshot) {
                  return snapshot.hasData
                      ? ListView.builder(
                          itemCount: snapshot.data.length,
                          itemBuilder: (_, int position) {
                            final item = snapshot.data[position];
                            //get your item data here ...
                            return Card(
                              child: ListTile(
                                title: Text(
                                    "Employee Name: " + snapshot.data[position].row[1]),
                              ),
                            );
                          },
                        )
                      : Center(
                          child: CircularProgressIndicator(),
                        );
                },
              ),
            );
          }
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Great Answer, however could be simplified slightly :) "Employee Name: " + item.row[1]
3

This might not be correct code, since I've not tested this, but this is how list view builder works and try using async await. Cleans up code quite a bit!

import 'package:flutter/material.dart';
import 'package:flutter_with_db_single_helper/helpers/database_helper.dart'

class EmployeesListScreen extends StatefulWidget {
    @override
    _EmployeesListScreenState createState() => _EmployeesListScreenState();
}

class _EmployeesListScreenState extends State<EmployeesListScreen> {

    List<String> _records;
    @override
    initState(){
        super.initState();
    }

    Future<void> _getRecords() async {
        var res = await db.getAllRecords("tabEmployee"); 
        setState((){
            _records = res;
        });
    }

    @override
    Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
        title: Text('List Of Employees'),
        ),
        body: _records==null ? Container():ListView.builder(
        itemCount: _records.length,
        itemBuilder: (_, int position) {
            return Card(
            child: ListTile(
                title:
                    Text("Employee Name: ", _records[position]),
            ),
            );
        },
        ),
    );
    }
}

Or you can use a future builder, as the other answer shows. :)

2 Comments

It was a good approach. Thanx for the help. I used FutureBuilder though.
you solved my problem, one thing should be added, _getRecords() should be called in initState();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.