在Flutter中使用Sqflite数据库插入内容后自动加载UI中的内容,涉及到以下几个基础概念:
Future
和async/await
来处理。StatefulWidget
和setState
方法来更新UI。以下是一个简单的示例,展示如何在Flutter中使用Sqflite插入数据并自动加载到UI中:
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Sqflite Example')),
body: MyHomePage(),
),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Map<String, dynamic>> _items = [];
Database? _database;
@override
void initState() {
super.initState();
initDatabase();
}
Future<void> initDatabase() async {
_database = await openDatabase(
'my_database.db',
version: 1,
onCreate: _onCreate,
);
loadData();
}
Future<void> _onCreate(Database db, int version) async {
await db.execute(
'CREATE TABLE items(id INTEGER PRIMARY KEY, name TEXT)',
);
}
Future<void> insertData() async {
int id = await _database!.insert('items', {'name': 'New Item'});
print('Inserted item with id: $id');
loadData();
}
Future<void> loadData() async {
List<Map<String, dynamic>> items = await _database!.query('items');
setState(() {
_items = items;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: [
ElevatedButton(
onPressed: insertData,
child: Text('Insert Data'),
),
Expanded(
child: ListView.builder(
itemCount: _items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_items[index]['name']!),
);
},
),
),
],
);
}
}
initState
中正确初始化数据库,并且数据库路径正确。setState
方法来通知Flutter框架UI需要重新构建。async
函数中进行,并正确处理Future
。通过以上步骤和示例代码,你可以在Flutter中实现将内容插入Sqflite数据库后自动加载到UI中的功能。
领取专属 10元无门槛券
手把手带您无忧上云