当我运行我的项目编译器是给我这个语句“LateInitializationError:字段'Db'具有”我无法修复此问题。当我执行dabase_client.dart中的函数,即saveItem()函数时,它会产生问题,而函数Compiler会告诉我,在某些dart文件中,代码中存在问题。我将为您提供我的整个项目代码,以便您可以很容易地找到确切的问题,这是创建一个问题。
主省道
import 'package:flutter/material.dart';
import 'package:no_to_do_app/ui/home.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
debugShowCheckedModeBanner: false,
title: 'NotoDo',
home: new Home(),
);
}
}
字符串
回家dart
import 'package:flutter/material.dart';
import 'package:no_to_do_app/ui/notodo_screen.dart';
class Home extends StatelessWidget {
const Home({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: Text('NoToDo'),
backgroundColor: Colors.black54,
),
body: new NoToDoScreen(
)
);
}
}
型
database_client.dart
import 'dart:async';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:no_to_do_app/model/nodo_item.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
class DatabaseHelper
{
static final DatabaseHelper _instance = DatabaseHelper.private();
DatabaseHelper.private();
factory DatabaseHelper() => _instance;
final String tableName = "nodoTbl";
final String columnId = "id";
final String columnItemName = "itemName";
final String columnDateCreated = "dateCreated";
static late Database _db;
Future<Database> get database async
{
/*if(_db!=null)
{
return _db;
}*/
_db =await initDb();
return _db;
}
DatabaseHelper.internal();
initDb() async
{
Directory documentDirectory = await getApplicationDocumentsDirectory();
String path = join(documentDirectory.path, "notodo_db.db");
var ourDb= await openDatabase(path , version: 1 , onCreate: _onCreate);
return ourDb;
}
void _onCreate(Database db, int version) async
{
await db.execute(
"CREATE TABLE $tableName(id INTEGER PRIMARY KEY , $columnItemName TEXT ,$columnDateCreated TEXT)"
);
debugPrint('Table is Created');
}
Future<int> saveItem(NoDoItem item) async
{
var dbClient = await database;
int res =await dbClient.insert(tableName, item.toMap());
debugPrint(res.toString());
return res;
}
Future<List> getItems() async
{
var dbClient = await database;
var result = await dbClient.rawQuery("SELECT * FROM $tableName ORDER BY $columnItemName ASC");
return result.toList();
}
Future<int?> getCount() async
{
var dbClient = await database;
return Sqflite.firstIntValue(await dbClient.rawQuery(
"SELECT COUNT(*) FROM $tableName"
));
}
Future<NoDoItem?> getItem(int id) async{
var dbClient = await database;
var result = await dbClient.rawQuery("SELECT * FROM $tableName WHERE id=$id");
//if(result.length==0) return null;
if(result.isEmpty) return null;
return NoDoItem.fromMap(result.first);
}
Future<int> deleteItem(int id) async
{
var dbClient =await database;
return await dbClient.delete(tableName,where: "$columnId = ?", whereArgs: [id]);
}
Future<int> updateItem(NoDoItem item) async
{
var dbClient =await database;
return await dbClient.update(tableName, item.toMap(),
where: "$columnId=?", whereArgs: [item.id]);
}
Future close() async
{
var dbClient =await database;
return dbClient.close();
}
}
型
nodo_item.dart**
import 'package:flutter/material.dart';
class NoDoItem extends StatelessWidget {
late String _itemName;
late String _dateCreated;
late int _id;
NoDoItem( this._itemName , this._dateCreated, {Key? key}) : super(key: key);
NoDoItem.map(dynamic obj, {Key? key}) : super(key: key)
{
_itemName = obj['ItemName'];
_dateCreated = obj['DateCreated'];
_id = obj['id'];
}
String get itemName => _itemName;
String get dateCreated => _dateCreated;
int get id => _id;
Map<String , dynamic>toMap()
{
var map = <String , dynamic>{};
map['ItemName'] = _itemName;
map['DateCreated'] = _dateCreated;
/*if(_id !=null)
{
map['id'] = _id;
}*/
map['id'] = _id;
return map;
}
NoDoItem.fromMap(Map<String , dynamic>map, {Key? key}) : super(key: key)
{
_itemName = map['ItemName'];
_dateCreated = map['DateCreated'];
_id = map['id'];
}
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.all(8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(_itemName ,
style: const TextStyle(
color: Colors.white,
fontSize: 16.5,
fontWeight: FontWeight.bold
),),
Container(
margin: const EdgeInsets.only(top: 5.0),
child: Text('Created on: $_dateCreated',
style: const TextStyle(
color: Colors.white70,
fontStyle: FontStyle.italic,
fontSize: 13.4
),),
)
],
)
);
}
}
型
notodo_screen.dart
import 'package:flutter/material.dart';
import 'package:no_to_do_app/model/nodo_item.dart';
import 'package:no_to_do_app/util/database_client.dart';
class NoToDoScreen extends StatefulWidget {
const NoToDoScreen({Key? key}) : super(key: key);
@override
_NoToDoScreenState createState() => _NoToDoScreenState();
}
class _NoToDoScreenState extends State<NoToDoScreen> {
final TextEditingController _textEditingController = TextEditingController();
var db = DatabaseHelper();
void _hndleSubmitted(String text) async
{
_textEditingController.clear();
NoDoItem noDoItem = NoDoItem(text,DateTime.now().toIso8601String());
int savedItemId = await db.saveItem(noDoItem);
debugPrint("Item saved ID: $savedItemId");
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black87,
body: Column(),
floatingActionButton: FloatingActionButton(
tooltip: 'Add Item',
backgroundColor: Colors.redAccent,
child: const ListTile(
title: Icon(Icons.add)
),
onPressed: _showFormDialog),
);
}
void _showFormDialog() {
var alert = AlertDialog(
content: Row(
children: [
Expanded(
child: TextField(
controller: _textEditingController,
autofocus: true,
decoration: const InputDecoration(
labelText: 'item',
hintText: "eg. Don't buy Stuff",
icon: Icon(Icons.add_circle_outline_outlined)
),
))
],
),
actions:[
TextButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(Colors.blue),
),
onPressed: ()
{
_hndleSubmitted(_textEditingController.text);
_textEditingController.clear();
},
child: const Text("Save"),
),
TextButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(Colors.blue),
),
onPressed:() => Navigator.pop(context),
child: const Text("Cancel"),)
]
);
showDialog(context: context,
builder:(_)
{
return alert;
});
}
}
型
编译器显示错误
E/flutter ( 3777): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: LateInitializationError: Field '_id@21016470' has not been initialized.
E/flutter ( 3777): #0 NoDoItem._id (package:no_to_do_app/model/nodo_item.dart)
E/flutter ( 3777): #1 NoDoItem.toMap (package:no_to_do_app/model/nodo_item.dart:31:17)
E/flutter ( 3777): #2 DatabaseHelper.saveItem (package:no_to_do_app/util/database_client.dart:54:53)
E/flutter ( 3777): <asynchronous suspension>
E/flutter ( 3777): #3 _NoToDoScreenState._hndleSubmitted (package:no_to_do_app/ui/notodo_screen.dart:20:23)
E/flutter ( 3777): <asynchronous suspension>
E/flutter ( 3777):
型
3条答案
按热度按时间a7qyws3x1#
后期值需要初始值,你需要初始化它。你的代码没有这个。试试这个:
字符串
n9vozmp42#
好的,我已经修复了这个问题,我没有初始化我的代码中的后期字段,然后没有初始化
字符串
正确的方法是
型
和itemId是主键,它不应该被初始化,因为数据库将把它的值自动为我们,因为它是主键,我们应该使它空通过放置?即
型
vzgqcmou3#
你的代码没问题,但替换静态后期Database _db;静态数据库?_db;