Flutter中使用sqlite
在Flutter中使用SQLite,你需要使用sqflite
包,这是一个插件,提供了一个在iOS和Android上使用的SQLite数据库的Dart API。
首先,在你的pubspec.yaml
文件中添加sqflite
作为依赖项:
dependencies:
flutter:
sdk: flutter
sqflite: ^1.3.2
然后,运行pub get
来安装依赖。
以下是一个简单的例子,展示了如何在Flutter中创建和使用SQLite数据库:
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Database _database;
@override
void initState() {
super.initState();
_initDatabase();
}
// 初始化数据库
_initDatabase() async {
// 获取数据库路径
final databasesPath = await getDatabasesPath();
final path = join(databasesPath, 'my_database.db');
// 打开或创建数据库
_database = await openDatabase(path, version: 1, onCreate: (db, version) async {
await db.execute('CREATE TABLE User (id INTEGER PRIMARY KEY, name TEXT, email TEXT)');
});
}
// 插入数据
_insertUser(User user) async {
await _database.insert('User', user.toMap(), conflictAlgorithm: ConflictAlgorithm.replace);
}
// 查询数据
_getAllUsers() async {
final List<Map<String, dynamic>> maps = await _database.query('User');
return maps.map((map) => User.fromMap(map)).toList();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("SQLite Example"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// 插入按钮
RaisedButton(
child: Text("Insert User"),
onPressed: () => _insertUser(User(name: 'John Doe', email: 'john@example.com')),
),
// 查询按钮
RaisedButton(
child: Text("Get All Users"),
onPressed: () async {
final users = await _getAllUsers();
print(users);
},
),
],
),
),
);
}
}
class Use
评论已关闭