Flutter 错误:_TypeError(类型“Null”不是“FutureOr<Database>”类型的子类型)
Posted
技术标签:
【中文标题】Flutter 错误:_TypeError(类型“Null”不是“FutureOr<Database>”类型的子类型)【英文标题】:Flutter Error: _TypeError (type 'Null' is not a subtype of type 'FutureOr<Database>') 【发布时间】:2021-09-15 09:29:13 【问题描述】:在 assets 文件夹中打开 sqlite 数据库。但我得到这个错误。 我试过'return _db ?? = 等待 initDb(); ' 但这是行不通的。 我不明白为什么我得到这个错误.. 请帮帮我..
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:bankingapp/models/histories.dart';
import 'package:flutter/services.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
class DbHelper
static Database? _db;
Future<Database> get db async
return _db = await initDb(); // <-- error is here
initDb() async
var dbDir = await getDatabasesPath();
var dbPath = join(dbDir, "app.db");
// Delete any existing database:
await deleteDatabase(dbPath);
// Create the writable database file from the bundled demo database file:
ByteData data = await rootBundle.load("assets/database/bankingapp.db");
List<int> bytes =
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(dbPath).writeAsBytes(bytes);
var db = await openDatabase(dbPath);
/*
var dbFolder = await getDatabasesPath();
String path = join(dbFolder, 'app.db');
return await openDatabase(path);*/
Future<List<Histories>> getHistories() async
var dbClient = await db;
var result = await dbClient.rawQuery("SELECT * FROM Histories");
return result.map((data) => Histories.fromMap(data)).toList();
【问题讨论】:
你检查过this吗? 是的,但我什么都不懂:/ 【参考方案1】:此代码将帮助您。
Future<Database> initDb() async
var dbFolder = await getDatabasesPath();
String path = join(dbFolder, 'app.db');
// Delete any existing database:
await deleteDatabase(path);
// Create the writable database file from the bundled demo database file:
try
await Directory(dirname(path)).create(recursive: true);
catch (_)
ByteData data =
await rootBundle.load(join("assets/database", "bankingapp.db"));
List<int> bytes =
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await new File(path).writeAsBytes(bytes, flush: true);
//open the database
return await openDatabase(path);
【讨论】:
以上是关于Flutter 错误:_TypeError(类型“Null”不是“FutureOr<Database>”类型的子类型)的主要内容,如果未能解决你的问题,请参考以下文章
_TypeError(类型 '_InternalLinkedHashMap<String, dynamic>' 不是类型 'Iterable<dynamic>' 的子类型) F
Flutter:当我尝试访问 JSON 数据的元素时出现 TypeError
TypeError:无法读取 null 的属性“Symbol(dartx._get)”(在 Flutter 中添加 Firestore 侦听器时)
Flutter web Firebase 分析类型错误:dart.global.firebase.analytics 不是函数