[英]How to get the length of Future<List> from Assets in Flutter
[英]How to get values from Future<List> in Flutter
我想從 sqflite 數據庫中獲取價值到 flutter 中的列表。 這是我的 model class
class Task {
final int id;
final String title;
final String description;
final String dateTime;
Task({this.id, this.title, this.description, this.dateTime});
Map<String, dynamic> toMap() {
return {
'id':id,
'title': title,
'description': description,
'dateTime': dateTime,
};
}
這是用於插入和檢索數據的 databaseHelper class。
class DatabaseHelper {
DatabaseHelper._();
static final DatabaseHelper db = DatabaseHelper._();
Database _database;
Future<Database> get database async {
if (_database != null) return _database;
_database = await _createDatabase();
return _database;
}
Future<Database> _createDatabase() async {
return await openDatabase(join(await getDatabasesPath(), 'task.db'),
onCreate: (db, version) {
return db.execute(
"CREATE TABLE tasks(id INTEGER PRIMARY KEY AUTO_INCREMENT , title TEXT, description TEXT, dateTime TEXT)",
);
}, version: 1);
}
Future<List<Task>> tasks() async {
final Database db = await database;
final maps = await db.query('tasks');
return List.generate(maps.length, (i) {
return Task(
id: maps[i]['id'],
title: maps[i]['title'],
description: maps[i]['description'],
dateTime: maps[i]['dateTime']
);
});
}
Future<void> insertTask(Task task) async {
final db = await database;
await db.insert(
'tasks',
task.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
}
當我使用 print(await tasks()) 時,它會在控制台中顯示 [Instance of 'Task', Instance of 'Task']。 這是一個錯誤嗎? 我想知道如何使用 DatabaseHelper class 中的 task() function 從數據庫中獲取值。
使用future builder,它需要future,並且只要future的object發生變化就會構建。
當我使用 print(await tasks()) 時,它會在控制台中顯示 [Instance of 'Task', Instance of 'Task']。 這是一個錯誤嗎?
發生這種情況是因為您沒有覆蓋toString()
。 沒有toString()
你只會得到默認的字符串轉換“ XXX實例”:
class Example {}
void main() async {
print(Example()); // Instance of 'Example'
}
通過覆蓋toString()
,您可以自定義 output:
class Example {
@override
String toString() => "My custom Example!";
}
void main() async {
print(Task()); // My custom Example!
}
我想知道如何使用 task() 從數據庫中獲取值
Flutter 中等待Future<T>
的最常見方法是使用FutureBuilder<T>
小部件。 這非常方便,因為它可以顯示進度指示器(讓用戶知道后台正在發生某些事情),稍后將替換為實際數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.