Unhandled Exception: NoSuchMethodError: The method 'insert' was called on null. Flutter
Unhandled Exception: NoSuchMethodError: The method 'insert' was called on null. Flutter
我修改了基本 sqlLite
示例以适应更动态的列表。但这可能不是最好的方法。无论如何,Database
代码如下所示:
import 'package:sqflite/sqflite.dart';
import 'package:sqflite/sqlite_api.dart';
import 'Entry.dart';
import 'package:path/path.dart';
class Database_ {
Future<Database> database ;
void openDBFunction() async {
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'Journal Entries.db');
database = openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute(
"CREATE TABLE entries( _entry TEXT, _date TEXT)"
);
});
}
Future<void> insertEntry(Entry entry) async {
final Database db = await database;
await db.insert(
'entry',
entry.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<List<Entry>> entries() async {
final Database db = await database;
final List<Map<String, dynamic>> maps = await db.query('entries');
return List.generate(maps.length, (i) {
return Entry(
maps[i]["_entry"],
maps[i]["_date"],
);
});
}
}
main.dart
看起来像这样:
import 'package:flutter/material.dart';
import 'package:slide_journal/MainPage.dart';
import 'package:flutter/widgets.dart';
import 'package:slide_journal/Database_.dart';
main()async {
WidgetsFlutterBinding.ensureInitialized();
Database_().openDBFunction();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData.dark(),
home: MainPage(),
);
}
}
然后这是输入页面:
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:slide_journal/Database_.dart';
import 'package:slide_journal/Entry.dart';
import 'List_of_Entries.dart';
// ignore: must_be_immutable
class MainPage extends StatelessWidget{
TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.vertical(bottom: Radius.circular(30))),
title: Text("Home"),
toolbarHeight: 50,
automaticallyImplyLeading: false,
actions:<Widget> [IconButton(
icon: Icon(Icons.list_alt_sharp),
onPressed: () =>{
Navigator.push(context, (MaterialPageRoute(builder: (context)=>ListOfEntries())))
},
),
]
),
drawer: new Drawer(
child: new ListView(
children: <Widget>[
new DrawerHeader(
child: Text("Trisha is baby", style: new TextStyle(fontSize: 20),),
)
],
),
),
body: Center(
child: SingleChildScrollView(
child: Column(
children: [
Container(
height: 600,
width: 350,
child: TextField(
enabled: true,
controller: _controller,
enableSuggestions: true,
decoration: InputDecoration(
hintText: "Use text, emojis...",
suffixIcon: IconButton(
onPressed: () => {
addEntry(_controller.toString(), "DateTime.now().toString()"),
},
icon: Icon(Icons.send_outlined),
),
),
keyboardType: TextInputType.multiline,
style: TextStyle(fontSize: 30),
maxLength: 100,
),
)
],
),
)
),
);
}
void addEntry(String entry_, String date_)async {
final entry = Entry(
entry_,
date_
);
Database_().insertEntry(entry);
}
}
这是错误:
[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: NoSuchMethodError: The method 'insert' was called on null.
database
未初始化。在将对象转换为它之前必须对其进行初始化。
数据库未在您的应用中初始化。如下操作
class DatabaseHelper {
static String tableName = 'entries';
static late Database _database;
static Future<Database> get database async {
final databasePath = await getDatabasesPath();
final status = await databaseExists(databasePath);
if (!status) {
_database = await openDatabase(join(databasePath, 'notes_database.db'),
onCreate: (database, version) {
return database.execute(
"CREATE TABLE entries( _entry TEXT, _date TEXT)"
);
}, version: 1);
}
return _database;
}
static Future<bool> insertDb(Model yourModel) async {
final db = await database;
try {
await db.insert(your insert cmd);
} on Error {
throw Error();
}
return true;
}
}
我修改了基本 sqlLite
示例以适应更动态的列表。但这可能不是最好的方法。无论如何,Database
代码如下所示:
import 'package:sqflite/sqflite.dart';
import 'package:sqflite/sqlite_api.dart';
import 'Entry.dart';
import 'package:path/path.dart';
class Database_ {
Future<Database> database ;
void openDBFunction() async {
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'Journal Entries.db');
database = openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute(
"CREATE TABLE entries( _entry TEXT, _date TEXT)"
);
});
}
Future<void> insertEntry(Entry entry) async {
final Database db = await database;
await db.insert(
'entry',
entry.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<List<Entry>> entries() async {
final Database db = await database;
final List<Map<String, dynamic>> maps = await db.query('entries');
return List.generate(maps.length, (i) {
return Entry(
maps[i]["_entry"],
maps[i]["_date"],
);
});
}
}
main.dart
看起来像这样:
import 'package:flutter/material.dart';
import 'package:slide_journal/MainPage.dart';
import 'package:flutter/widgets.dart';
import 'package:slide_journal/Database_.dart';
main()async {
WidgetsFlutterBinding.ensureInitialized();
Database_().openDBFunction();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData.dark(),
home: MainPage(),
);
}
}
然后这是输入页面:
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:slide_journal/Database_.dart';
import 'package:slide_journal/Entry.dart';
import 'List_of_Entries.dart';
// ignore: must_be_immutable
class MainPage extends StatelessWidget{
TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.vertical(bottom: Radius.circular(30))),
title: Text("Home"),
toolbarHeight: 50,
automaticallyImplyLeading: false,
actions:<Widget> [IconButton(
icon: Icon(Icons.list_alt_sharp),
onPressed: () =>{
Navigator.push(context, (MaterialPageRoute(builder: (context)=>ListOfEntries())))
},
),
]
),
drawer: new Drawer(
child: new ListView(
children: <Widget>[
new DrawerHeader(
child: Text("Trisha is baby", style: new TextStyle(fontSize: 20),),
)
],
),
),
body: Center(
child: SingleChildScrollView(
child: Column(
children: [
Container(
height: 600,
width: 350,
child: TextField(
enabled: true,
controller: _controller,
enableSuggestions: true,
decoration: InputDecoration(
hintText: "Use text, emojis...",
suffixIcon: IconButton(
onPressed: () => {
addEntry(_controller.toString(), "DateTime.now().toString()"),
},
icon: Icon(Icons.send_outlined),
),
),
keyboardType: TextInputType.multiline,
style: TextStyle(fontSize: 30),
maxLength: 100,
),
)
],
),
)
),
);
}
void addEntry(String entry_, String date_)async {
final entry = Entry(
entry_,
date_
);
Database_().insertEntry(entry);
}
}
这是错误:
[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: NoSuchMethodError: The method 'insert' was called on null.
database
未初始化。在将对象转换为它之前必须对其进行初始化。
数据库未在您的应用中初始化。如下操作
class DatabaseHelper {
static String tableName = 'entries';
static late Database _database;
static Future<Database> get database async {
final databasePath = await getDatabasesPath();
final status = await databaseExists(databasePath);
if (!status) {
_database = await openDatabase(join(databasePath, 'notes_database.db'),
onCreate: (database, version) {
return database.execute(
"CREATE TABLE entries( _entry TEXT, _date TEXT)"
);
}, version: 1);
}
return _database;
}
static Future<bool> insertDb(Model yourModel) async {
final db = await database;
try {
await db.insert(your insert cmd);
} on Error {
throw Error();
}
return true;
}
}