sqflite

数据库取数据是一个Future类型的函数完成的,为此用数据库数据构建部件得用FutureBuilder构建;
如下函数就是Future类型的从数据库取数据的函数;
Future getBaseData() async {
await dataBase.open();
return await dataBase.queryAll();
}函数类型是Future,这就是为什么用数据库构建部件得用FutureBuilder的原因;
采用FutureBuilder构建部件,第一步就得判断if(snapshot.hasdata)如果有数据在继续操作,否则可以返回一个加载页面等待;



数据库类型数据的赋值是通过如下代码实现的:
db=await openDatabase(path,version: 1,onCreate: (db,ver)async{
await db.execute('''
Create Table post(
userId integer,
id integer primary key,
title text,
body text
);
''');
});也就是说打开数据库返回的是一个数据库类型的数据,'''这里是多行SQL代码''',注意类型是:integer text, 不是 int String;


注意:数据库操作和网络操作基本上都是异步操作,牢记()async{await}

下面是两个示例(可以对比来看看):
第一个示例包括两个文件,main.dart 和
SqliteHelper.dart

import 'package:flutter/material.dart';

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:demo0506/SqliteHelper.dart';

void main()=>runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
final String url='http://jsonplaceholder.typicode.com/posts';
final sqlHelp=SqliteHelper();
getAllPost()async{
await sqlHelp.open();
return await sqlHelp.queryAll();
}
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
child: Icon(Icons.http),
onPressed: ()async{
await sqlHelp.open();
var response = await http.get(url);
List listData = jsonDecode(response.body);
listData.forEach((e) async => await sqlHelp.insert(e));//强调:给数据库写数据之前必须确定数据库是空的才可以写,如果不是空的就先清空再写;
setState(() {

});
}),
appBar: AppBar(title: Text('DataBase'),),
body: FutureBuilder(
future: getAllPost(),
builder: (BuildContext context,snapshot){
if(snapshot.hasData){
List _listData=snapshot.data;
return ListView.builder(
itemCount: _listData.length,
itemBuilder: (context,index){
return InkWell(
onTap:()async{
await sqlHelp.delete(_listData[index]['id']);
setState(() {

});
},
child: ListTile(title: Text(_listData[index]['title']),));
},);
}
return Container();
}
),
);
}
}





import 'package:sqflite/sqflite.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http ;

class SqliteHelper{
final sqlFileName='mydb.sql';
final table='post';
Database db;
open()async{
String path = '${await getDatabasesPath()}/$sqlFileName';//getDatabasesPath()这句代码必须放在()async{await 此处}方能打开;
    if(db==null){
db=await openDatabase(path,version: 1,onCreate: (db,ver)async{
await db.execute('''
Create Table post(
id integer primary key,
userId integer,
title text,
body text
);
''');
});
}
}
insert(Map<String, dynamic> map)async{
await db.insert(table, map);
}
queryAll()async{
return await db.query(table,columns: null);
}
delete(int id)async{
return await db.delete(table,where: 'id=$id');
}
}



再附上一个新的示例:
import 'package:flutter/material.dart';
import 'database.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
String path = 'http://jsonplaceholder.typicode.com/posts';
final dataBase=DataBase();
getBaseData() async {
await dataBase.open();
return await dataBase.queryAll();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('大综合'),
flexibleSpace: Image.network('http://www.ecobentech.com/images/7.jpg',fit: BoxFit.cover,),
),
body: FutureBuilder(
future: getBaseData(),
builder:(context,snapshot){
if(snapshot.hasData){
List listdata=snapshot.data;
return ListView.builder(
itemCount: listdata.length,
itemBuilder: (context,index){
return InkWell(
onTap: ()async{
await dataBase.open();
await dataBase.delete(listdata[index]['id']);
setState(() {

});
},
child: ListTile(
title: Text(listdata[index]['title']),
subtitle: Text(listdata[index]['body']),
),
);
});
}else{
return Center(child: CircularProgressIndicator(),);
}
},
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.send),
onPressed: () async {
if(dataBase.db==null){
await dataBase.open();
var response = await http.get(path);
List listData = jsonDecode(response.body);
listData.forEach((e) async => await dataBase.insert(e));
setState(() {});
}else{
showDialog(context: context,builder: (context){
return SimpleDialog(
shape: CircleBorder(side: BorderSide(color: Colors.orangeAccent, style: BorderStyle.solid, width: 2)),
title: Text('database has data'),
contentPadding: EdgeInsets.all(28),
children: <Widget>[
ChoiceChip(label: Text('香蕉'), selectedColor: Colors.orangeAccent,selected: true,),
ChoiceChip(label: Text('苹果'), selected: true,),
ChoiceChip(label: Text('橘子'), selected: true,),
],
);
});
}

},
),
);
}
}

import 'package:sqflite/sqflite.dart';
import 'package:flutter/material.dart';

class DataBase{
final sqlFileName='mydbb.sql';
final table='post';
Database db;
open()async{
String path = '${await getDatabasesPath()}/$sqlFileName';
if(db==null){
db=await openDatabase(path,version: 1,onCreate: (db,ver)async{
await db.execute('''
Create Table post(
userId integer,
id integer primary key,
title text,
body text
);
''');
});
}else{
return AlertDialog(title: Text('database is full'),);
}
}
insert(Map<String, dynamic> map)async{
await db.insert(table, map);
}
queryAll()async{
return await db.query(table,columns: null);
}
delete(int id)async{
return await db.delete(table,where: 'id=$id');
}
}







posted @ 2019-05-06 22:52  braveheart007  阅读(267)  评论(0编辑  收藏  举报