Flutter数据库管理插件sqlite_handler的使用
Flutter数据库管理插件sqlite_handler的使用
Sqlite Handler 是一个轻量级的包,用于通过编写数据库名称及其字段来处理 SQLite 数据库,并调用该包中的方法以完成数据库查询,包括创建、删除、修改和查询等操作。
开始使用
以下是一个完整的示例,展示了如何在 Flutter 应用程序中使用 sqlite_handler
插件。
示例代码
import 'package:flutter/material.dart';
import 'package:sqlite_handler/model.dart';
import 'package:sqlite_handler_example/tables.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 创建表结构
Migrations.createTables(tables);
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('SQLite Handler 示例应用'),
),
body: Center(
child: TextButton(
child: const Text('运行示例'),
onPressed: () async {
// 插入多个用户数据
await UserModel(
name: "Allen",
email: "allen@ana.com",
password: "123456789",
isActive: true,
createdAt: DateTime.now(),
bio: "Allen")
.insert();
await UserModel(
name: "Teddy",
email: "teddy@ana.com",
password: "123456789",
isActive: true,
createdAt: DateTime.now(),
bio: "Teddy")
.insert();
await UserModel(
name: "Mark",
email: "mark@ana.com",
password: "123456789",
isActive: true,
createdAt: DateTime.now(),
bio: "Mark")
.insert();
await UserModel(
name: "James",
email: "hames@ana.com",
password: "123456789",
isActive: true,
createdAt: DateTime.now(),
bio: "James")
.insert();
await UserModel(
name: "Kim",
email: "kim@ana.com",
password: "123456789",
isActive: true,
createdAt: DateTime.now(),
bio: "Kim")
.insert();
await UserModel(
name: "Paul",
email: "paul@ana.com",
password: "123456789",
isActive: false,
createdAt: DateTime.now(),
bio: "Paul")
.insert();
await UserModel(
name: "ali",
email: "ana@ana.com",
password: "123456789",
isActive: true,
createdAt: DateTime.now(),
bio: "annna")
.insert();
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
// 获取指定字段的数据
print(await PersonsModel().pluck(['id', 'name']));
// 这里可以添加更多操作,例如查询、更新、删除等
},
child: const Text("点击我"),
),
),
);
}
}
// 用户模型类
class UserModel extends Model {
int? id;
String? email, password, name, bio;
bool? isActive;
DateTime? createdAt;
UserModel(
{this.id,
this.email,
this.password,
this.name,
this.bio,
this.createdAt,
this.isActive})
: super('users');
@override
UserModel fromMap(Map<dynamic, dynamic> map) =>
UserModel(
id: map['id'],
email: map['email'],
password: map['password'],
bio: map['bio'],
name: map['name'],
isActive: getBool(map['is_active']),
createdAt: getDateTime(map['created_at']),
);
@override
Map<String, Object?> toMap() =>
{
'id': id,
'email': email,
'password': password,
'bio': bio,
'name': name,
'is_active': isActive,
'created_at': createdAt,
};
}
// 人员模型类
class PersonsModel extends Model {
int? id, userId;
String? email, password, name;
DateTime? createdAt;
PersonsModel(
{this.id,
this.email,
this.password,
this.name,
this.createdAt,
this.userId})
: super('persons');
@override
PersonsModel fromMap(Map<dynamic, dynamic> map) =>
PersonsModel(
id: map['id'],
email: map['email'],
password: map['password'],
name: map['name'],
userId: map['user_id'],
createdAt: getDateTime(map['created_at']),
);
@override
Map<String, Object?> toMap() =>
{
'id': id,
'email': email,
'password': password,
'name': name,
'user_id': userId,
'created_at': createdAt,
};
}
代码解释
-
导入必要的包:
import 'package:flutter/material.dart'; import 'package:sqlite_handler/model.dart'; import 'package:sqlite_handler_example/tables.dart';
-
初始化应用:
void main() async { WidgetsFlutterBinding.ensureInitialized(); // 创建表结构 Migrations.createTables(tables); runApp(const MyApp()); }
-
定义主应用类:
class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); }
-
定义应用状态类:
class _MyAppState extends State<MyApp> { @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('SQLite Handler 示例应用'), ), body: Center( child: TextButton( child: const Text('运行示例'), onPressed: () async { // 插入多个用户数据 await UserModel( name: "Allen", email: "allen@ana.com", password: "123456789", isActive: true, createdAt: DateTime.now(), bio: "Allen") .insert(); await UserModel( name: "Teddy", email: "teddy@ana.com", password: "123456789", isActive: true, createdAt: DateTime.now(), bio: "Teddy") .insert(); await UserModel( name: "Mark", email: "mark@ana.com", password: "123456789", isActive: true, createdAt: DateTime.now(), bio: "Mark") .insert(); await UserModel( name: "James", email: "hames@ana.com", password: "123456789", isActive: true, createdAt: DateTime.now(), bio: "James") .insert(); await UserModel( name: "Kim", email: "kim@ana.com", password: "123456789", isActive: true, createdAt: DateTime.now(), bio: "Kim") .insert(); await UserModel( name: "Paul", email: "paul@ana.com", password: "123456789", isActive: false, createdAt: DateTime.now(), bio: "Paul") .insert(); await UserModel( name: "ali", email: "ana@ana.com", password: "123456789", isActive: true, createdAt: DateTime.now(), bio: "annna") .insert(); }, ), ), floatingActionButton: FloatingActionButton( onPressed: () async { // 获取指定字段的数据 print(await PersonsModel().pluck(['id', 'name'])); }, child: const Text("点击我"), ), ), ); } }
-
定义用户模型类:
class UserModel extends Model { int? id; String? email, password, name, bio; bool? isActive; DateTime? createdAt; UserModel( {this.id, this.email, this.password, this.name, this.bio, this.createdAt, this.isActive}) : super('users'); @override UserModel fromMap(Map<dynamic, dynamic> map) => UserModel( id: map['id'], email: map['email'], password: map['password'], bio: map['bio'], name: map['name'], isActive: getBool(map['is_active']), createdAt: getDateTime(map['created_at']), ); @override Map<String, Object?> toMap() => { 'id': id, 'email': email, 'password': password, 'bio': bio, 'name': name, 'is_active': isActive, 'created_at': createdAt, }; }
-
定义人员模型类:
class PersonsModel extends Model { int? id, userId; String? email, password, name; DateTime? createdAt; PersonsModel( {this.id, this.email, this.password, this.name, this.createdAt, this.userId}) : super('persons'); @override PersonsModel fromMap(Map<dynamic, dynamic> map) => PersonsModel( id: map['id'], email: map['email'], password: map['password'], name: map['name'], userId: map['user_id'], createdAt: getDateTime(map['created_at']), ); @override Map<String, Object?> toMap() => { 'id': id, 'email': email, 'password': password, 'name': name, 'user_id': userId, 'created_at': createdAt, }; }
更多关于Flutter数据库管理插件sqlite_handler的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter数据库管理插件sqlite_handler的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter项目中使用sqlite_handler
插件进行数据库管理的代码示例。sqlite_handler
是一个流行的Flutter插件,用于简化SQLite数据库的操作。请注意,这个插件的具体API和功能可能会随着版本的更新而变化,因此以下代码基于插件的常见用法。
首先,确保你已经在pubspec.yaml
文件中添加了sqlite_handler
依赖:
dependencies:
flutter:
sdk: flutter
sqlite_handler: ^最新版本号 # 请替换为当前最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,创建一个Flutter项目,并在其中使用sqlite_handler
进行数据库操作。以下是一个简单的示例:
import 'package:flutter/material.dart';
import 'package:sqlite_handler/sqlite_handler.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter SQLite Handler Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late DatabaseHelper _dbHelper;
@override
void initState() {
super.initState();
_dbHelper = DatabaseHelper();
_initializeDatabase();
}
Future<void> _initializeDatabase() async {
// 创建表
await _dbHelper.createTable('users', columns: [
'id INTEGER PRIMARY KEY AUTOINCREMENT',
'name TEXT NOT NULL',
'email TEXT NOT NULL UNIQUE',
]);
// 插入数据
await _dbHelper.insert('users', {
'name': 'John Doe',
'email': 'john@example.com',
});
// 查询数据
List<Map<String, dynamic>> users = await _dbHelper.query('users');
print('Users: $users');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter SQLite Handler Demo'),
),
body: Center(
child: Text('Database initialized and data inserted!'),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
// 更新数据
await _dbHelper.update('users', {
'name': 'Jane Doe',
}, where: 'email = ?', whereArgs: ['john@example.com']);
// 查询更新后的数据
List<Map<String, dynamic>> updatedUsers = await _dbHelper.query('users');
print('Updated Users: $updatedUsers');
},
tooltip: 'Update Data',
child: Icon(Icons.edit),
),
);
}
}
class DatabaseHelper {
DatabaseHelper._();
static final DatabaseHelper instance = DatabaseHelper._();
late Database _database;
Future<Database> get database async {
if (_database == null) {
_database = await openDatabase(
join(await getDatabasesPath(), 'my_database.db'),
onCreate: (db, version) {
// 在这里可以创建数据库表等初始化操作
},
version: 1,
);
}
return _database;
}
Future<void> createTable(String tableName, {required List<String> columns}) async {
final Database db = await database;
String createTableQuery = 'CREATE TABLE IF NOT EXISTS $tableName (${columns.join(', ')})';
await db.execute(createTableQuery);
}
Future<void> insert(String tableName, Map<String, dynamic> values) async {
final Database db = await database;
String insertQuery = 'INSERT INTO $tableName (${values.keys.join(', ')}) VALUES (${values.values.map((value) => '?').join(', ')})';
await db.rawInsert(insertQuery, values.values.toList());
}
Future<List<Map<String, dynamic>>> query(String tableName) async {
final Database db = await database;
List<Map<String, dynamic>> result = await db.query(tableName);
return result;
}
Future<void> update(String tableName, Map<String, dynamic> values, {required String where, required List<Object?> whereArgs}) async {
final Database db = await database;
String updateQuery = 'UPDATE $tableName SET ${values.entries.map((entry) => '${entry.key} = ?').join(', ')} WHERE $where';
List<Object?> updateArgs = [...values.values, ...whereArgs];
await db.rawUpdate(updateQuery, updateArgs);
}
}
在这个示例中,我们定义了一个DatabaseHelper
类来封装数据库操作。这个类包含创建表、插入数据、查询数据和更新数据的方法。在MyHomePage
类中,我们在initState
方法中初始化了数据库,并插入了一条记录。同时,我们在浮动操作按钮的点击事件中演示了如何更新数据。
请注意,这个示例仅用于演示目的,实际应用中可能需要更复杂的错误处理和资源管理。此外,sqlite_handler
插件的具体API可能会有所不同,因此请参考插件的官方文档以获取最新和最准确的信息。