我正在将 sqflite 配置到我的应用中,以便能够执行粗体操作。我已经为此工作了好几天。
一切似乎都很好,但是当我尝试在路由中加载 widget 以便尝试进行Crud操作时,在调用窗口小部件类时,我不断遇到与参数有关的错误。
这可能是一个简单的问题,但由于我是初学者,所以无法弄清楚。
下面是 main.dart 文件。
import 'package:flutter/material.dart';
import 'home.dart';
import 'package:com.example.simple_app/pages/create_account/create_account_page.dart';
import 'package:com.example.simple_app/pages/add_person/add_person.dart';
import 'package:com.example.simple_app/models/user.dart';
void main() => runApp(SimpleApp());
final routes = {
'/': (BuildContext context) => new CreateAccountPage(),
class SimpleApp extends StatefulWidget {
@override
_SimpleAppState createState() => _SimpleAppState();
}
class _SimpleAppState extends State<SimpleApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Simple App',
theme: ThemeData(
primarySwatch: Colors.blueGrey,
),
initialRoute: '/',
routes: routes,
);
}
}
下面是 create_account_page.dart 文件
import 'package:flutter/material.dart';
import 'package:com.example.money_lender_app/models/user.dart';
class CreateAccountPage extends StatefulWidget {
final User user;
CreateAccountPage(this.user);
@override
CreateAccountPageState createState() => CreateAccountPageState(this.user);
}
//class controller
class CreateAccountPageState extends State<CreateAccountPage> {
User user;
CreateAccountPageState(this.user);
TextEditingController nameController = TextEditingController();
@override
Widget build(BuildContext context) {
//kondisi
if (user != null) {
nameController.text = user.name;
}
//rubah
return Scaffold(
appBar: AppBar(
title: user == null ? Text('Tambah') : Text('Rubah'),
leading: Icon(Icons.keyboard_arrow_left),
),
body: Padding(
padding: EdgeInsets.only(top: 15.0, left:10.0, right:10.0),
child: ListView(
children: <Widget> [
// nama
Padding (
padding: EdgeInsets.only(top:20.0, bottom:20.0),
child: TextField(
controller: nameController,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: 'Nama Lengkap',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0),
),
),
onChanged: (value) {
//
},
),
),
// tombol button
Padding (
padding: EdgeInsets.only(top:20.0, bottom:20.0),
child: Row(
children: <Widget> [
// tombol simpan
Expanded(
child: RaisedButton(
color: Theme.of(context).primaryColorDark,
textColor: Theme.of(context).primaryColorLight,
child: Text(
'Save',
textScaleFactor: 1.5,
),
onPressed: () {
// current datetime
var currentDate = new DateTime.now();
if (user == null) {
// tambah data
user = User(nameController.text, currentDate, currentDate);
} else {
// ubah data
user.name = nameController.text;
user.created_at = currentDate;
user.updated_at = currentDate;
}
// kembali ke layar sebelumnya dengan membawa objek user
Navigator.pop(context, user);
},
),
),
Container(width: 5.0,),
// tombol batal
Expanded(
child: RaisedButton(
color: Theme.of(context).primaryColorDark,
textColor: Theme.of(context).primaryColorLight,
child: Text(
'Cancel',
textScaleFactor: 1.5,
),
onPressed: () {
Navigator.pop(context);
},
),
),
],
),
),
],
),
)
);
}
}
下面是 db_helper.dart 文件。
import 'package:sqflite/sqflite.dart';
import 'dart:async';
//mendukug pemrograman asinkron
import 'dart:io';
//bekerja pada file dan directory
import 'package:path_provider/path_provider.dart';
import 'package:com.example.simple_app/models/user.dart';
//pubspec.yml
class DbHelper {
static DbHelper _dbHelper;
static Database _database;
DbHelper._createObject();
factory DbHelper() {
if (_dbHelper == null) {
_dbHelper = DbHelper._createObject();
}
return _dbHelper;
}
Future<Database> initDb() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path + 'simpleapp.db';
//create, read databases
var todoDatabase = openDatabase(path, version: 1, onCreate: _createDb);
return todoDatabase;
}
void _createDb(Database db, int version) async {
await db.execute('''
CREATE TABLE user (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
created_at DATETIME,
updated_at DATETIME
)
''');
}
Future<Database> get database async {
if (_database == null) {
_database = await initDb();
}
return _database;
}
Future<List<Map<String, dynamic>>> select() async {
Database db = await this.database;
var mapList = await db.query('user', orderBy: 'name');
return mapList;
}
//create databases
Future<int> insert(User object) async {
Database db = await this.database;
int count = await db.insert('user', object.toMap());
return count;
}
//update databases
Future<int> update(User object) async {
Database db = await this.database;
int count = await db.update('user', object.toMap(),
where: 'id=?',
whereArgs: [object.id]);
return count;
}
//delete databases
Future<int> delete(int id) async {
Database db = await this.database;
int count = await db.delete('user',
where: 'id=?',
whereArgs: [id]);
return count;
}
Future<List<User>> getUserList() async {
var userMapList = await select();
int count = userMapList.length;
List<User> userList = List<User>();
for (int i=0; i<count; i++) {
userList.add(User.fromMap(userMapList[i]));
}
return userList;
}
}
下面是 user.dart 文件。它在模型文件夹中。
class User {
int _id;
String _name;
String _username;
DateTime _created_at;
DateTime _updated_at;
// konstruktor versi 1
User(this._name, this._created_at, this._updated_at);
// konstruktor versi 2: konversi dari Map ke User
User.fromMap(Map<String, dynamic> map) {
this._id = map['id'];
this._name = map['name'];
this._created_at = map['created_at'];
this._updated_at = map['updated_at'];
}
// getter
int get id => _id;
String get name => _name;
DateTime get created_at => _created_at;
DateTime get updated_at => _updated_at;
// setter
set name(String value) {
_name = value;
}
set created_at(DateTime value) {
_created_at = value;
}
set updated_at(DateTime value) {
_updated_at = value;
}
Map<String, dynamic> toMap() {
Map<String, dynamic> map = Map<String, dynamic>();
map['id'] = this._id;
map['name'] = name;
map['created_at'] = created_at;
map['updated_at'] = updated_at;
return map;
}
}
pubspec.yaml 文件具有以下依赖性。
cupertino_icons: ^0.1.2
flutter_launcher_icons: ^0.7.4
sqflite: any
path_provider: ^1.5.1
我进入调试控制台的错误日志是这样的:
lib/main.dart:11:55: Error: Too few positional arguments: 1 required, 0 given.
'/': (BuildContext context) => new CreateAccountPage(),
^
lib/pages/create_account/create_account_page.dart:5:7: Context: Found this candidate, but the arguments don't match.
CreateAccountPage(this.user);
^^^^^^^^^^^^^^^^^
lib/main.dart:16:69: Error: Too few positional arguments: 1 required, 0 given.
'/create_account': (BuildContext context) => new CreateAccountPage(),
^
lib/pages/create_account/create_account_page.dart:5:7: Context: Found this candidate, but the arguments don't match.
CreateAccountPage(this.user);
^^^^^^^^^^^^^^^^^
我非常需要能够在CreateAccountPage()
内部传递正确的参数。
我希望这段代码能正常工作,而不会出现任何参数错误。谢谢!
答案 0 :(得分:0)
该错误表明您在调用CreateAccountPage()
时缺少参数。
其构造函数为CreateAccountPage(this.user)
,因此在创建帐户页面时需要提供User对象,或者从构造函数中删除参数。