Flutter-从数据库中获取记录并在ListView Builder中显示 [英] Flutter - Fetch records from database and display in ListView Builder
本文介绍了Flutter-从数据库中获取记录并在ListView Builder中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在研究Flutter项目并正在使用Sqflite数据库。我设法将数据保存在db中。现在,我试图根据表名称从数据库中获取所有记录的列表,并将其显示在 ListView.builder中。
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?
推荐答案
您可以使用FutureBuilder来获取和显示数据:
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(),
);
},
),
);
}
}
这篇关于Flutter-从数据库中获取记录并在ListView Builder中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文