首先我要鄙視一下那些博客寫一半的人(我叼他螺母),太坑了。
這邊就兩個文件main.dart和sqflite_page.dart
1.添加sqflite插件
在pubspec.yaml文件中添加sqflite,當前版本1.2.0:(別忘了點擊右上角的“Packages get”或者“Packages upgrade”)
輔助插件: fluttertoast: ^3.0.4
在lib下新建sqflite.dart文件:
則新建的sqflite.dart代碼如下:
import 'package:flutter/material.dart'; import 'package:sqflite/sqflite.dart'; import 'package:path/path.dart'; import 'package:fluttertoast/fluttertoast.dart'; class SqflitePage extends StatefulWidget{ @override State<StatefulWidget> createState() { // TODO: implement createState return _SqflitePageState(); } } class _SqflitePageState extends State<SqflitePage> { TextEditingController _nameController=new TextEditingController(); TextEditingController _ageController=new TextEditingController(); String _data = "暫無數據"; String _dbName = 'user.db';//數據庫名稱 String _createTableSQL ='CREATE TABLE student_table (id INTEGER PRIMARY KEY, name TEXT,age INTEGER)';//創建學生表; int _dbVersion = 1;//數據庫版本 @override void initState() { super.initState(); //創建數據庫、學生表 _createDb(_dbName, _dbVersion, _createTableSQL); } @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( iconTheme: IconThemeData(color: Colors.white), title: Text("sqflite數據存儲",style: TextStyle(color: Colors.white),), ), body: Container( padding: EdgeInsets.all(20), child: Column( children: <Widget>[ Center( child: Text("設置進入程序默認創建數據庫和一張學生表,如下可對表的姓名、年齡進行增刪改查操作:",style: TextStyle(fontSize: 14,color: Color(0xff666666)),), ), Padding(padding: EdgeInsets.only(top: 10)), _getNameInputView(), Padding(padding: EdgeInsets.only(top: 10)), _getAgeInputView(), Padding(padding: EdgeInsets.only(top: 30)), _getAddBtnView(), Padding(padding: EdgeInsets.only(top: 10)), _getdeleteBtnView(), Padding(padding: EdgeInsets.only(top: 10)), _getUpdateBtnView(), Padding(padding: EdgeInsets.only(top: 10)), _getQueryBtnView(), Padding(padding: EdgeInsets.only(top: 30)), Text(_data,style: TextStyle(color: Colors.red,fontSize: 18),) ], ), ), resizeToAvoidBottomPadding: false, ); } _getNameInputView() { return TextField( keyboardType: TextInputType.text, style: TextStyle(color: Color(0xFF888888)), controller: _nameController, decoration: InputDecoration( hintText: "姓名", hintStyle: TextStyle(color: Color(0xFF888888)), contentPadding: EdgeInsets.only(left: 10,right: 10,bottom: 10,top: 10), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8.0), ), ), ); } _getAgeInputView() { return TextField( keyboardType: TextInputType.text, style: TextStyle(color: Color(0xFF888888)), controller: _ageController, decoration: InputDecoration( hintText: "年齡", hintStyle: TextStyle(color: Color(0xFF888888)), contentPadding: EdgeInsets.only(left: 10,right: 10,bottom: 10,top: 10), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8.0), ), ), ); } _getAddBtnView(){ return RaisedButton( onPressed: (){ if(_nameController.text==null||_nameController.text==""){ Fluttertoast.showToast(msg: "插入數據不能為空!",backgroundColor: Colors.orange); return; } if(_ageController.text==null||_ageController.text==""){ Fluttertoast.showToast(msg: "插入數據不能為空!",backgroundColor: Colors.orange); return; } String sql = "INSERT INTO student_table(name,age) VALUES('${_nameController.text}','${_ageController.text}')"; _add(_dbName, sql); }, child: Text("插入數據",style: TextStyle(color: Colors.white,fontSize: 18),), color: Colors.orange, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5), ) ); } _getdeleteBtnView(){ return RaisedButton( onPressed: (){ String sql = "DELETE FROM student_table";//無條件刪除學生表數據 _delete(_dbName, sql); }, child: Text("刪除數據",style: TextStyle(color: Colors.white,fontSize: 18),), color: Colors.orange, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5), ) ); } _getUpdateBtnView(){ return RaisedButton( onPressed: (){ if(_nameController.text==null||_nameController.text==""){ Fluttertoast.showToast(msg: "姓名不能為空!",backgroundColor: Colors.orange); return; } String sql = "UPDATE student_table SET name =? WHERE id = ?"; _update(_dbName, sql,[_nameController.text,1]); }, child: Text("修改姓名數據",style: TextStyle(color: Colors.white,fontSize: 18),), color: Colors.orange, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5), ) ); } _getQueryBtnView(){ return RaisedButton( onPressed: (){ String sql = 'SELECT * FROM student_table'; _query(_dbName, sql); }, child: Text("查詢數據",style: TextStyle(color: Colors.white,fontSize: 18),), color: Colors.orange, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5), ) ); } ///創建數據庫db _createDb(String dbName,int vers,String dbTables) async { //獲取數據庫路徑 var databasesPath = await getDatabasesPath(); String path = join(databasesPath, dbName); print("數據庫路徑:$path數據庫版本$vers"); //打開數據庫 await openDatabase( path, version:vers, onUpgrade: (Database db, int oldVersion, int newVersion) async{ //數據庫升級,只回調一次 print("數據庫需要升級!舊版:$oldVersion,新版:$newVersion"); }, onCreate: (Database db, int vers) async{ //創建表,只回調一次 await db.execute(dbTables); await db.close(); } ); setState(() { _data = "成功創建數據庫db!\n數據庫路徑: $path \n數據庫版本$vers"; }); } ///增 _add(String dbName,String sql) async { //獲取數據庫路徑 var databasesPath = await getDatabasesPath(); String path = join(databasesPath, dbName); print("數據庫路徑:$path"); Database db = await openDatabase(path); await db.transaction((txn) async { int count = await txn.rawInsert(sql); }); await db.close(); setState(() { _data = "插入數據成功!"; }); } ///刪 _delete(String dbName,String sql) async { var databasesPath = await getDatabasesPath(); String path = join(databasesPath, dbName); Database db = await openDatabase(path); int count = await db.rawDelete(sql); await db.close(); if (count > 0) { setState(() { _data = "執行刪除操作完成,該sql刪除條件下的數目為:$count"; }); } else { setState(() { _data = "無法執行刪除操作,該sql刪除條件下的數目為:$count"; }); } } ///改 _update(String dbName,String sql,List arg) async { var databasesPath = await getDatabasesPath(); String path = join(databasesPath, dbName); Database db = await openDatabase(path); int count = await db.rawUpdate(sql,arg);//修改條件,對應參數值 await db.close(); if (count > 0) { setState(() { _data = "更新數據庫操作完成,該sql刪除條件下的數目為:$count"; }); } else { setState(() { _data = "無法更新數據庫,該sql刪除條件下的數目為:$count"; }); } } ///查條數 _getQueryNum(String dbName,String sql) async { var databasesPath = await getDatabasesPath(); String path = join(databasesPath, dbName); Database db = await openDatabase(path); int count = Sqflite.firstIntValue(await db.rawQuery(sql)); await db.close(); return count; } ///查全部 _query(String dbName,String sql) async { var databasesPath = await getDatabasesPath(); String path = join(databasesPath, dbName); Database db = await openDatabase(path); List<Map> list = await db.rawQuery(sql); await db.close(); setState(() { _data = "數據詳情:$list"; }); } }
main.dart中調用代碼如下:
import 'package:flutter/material.dart'; import 'package:flutter_data_storage/sqflite_page.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.orange, ), home: MyHomePage(title: 'Flutter學習'), routes: <String,WidgetBuilder>{ sqfliteRoute:(BuildContext context) => SqflitePage(), }, ); } } const String sqfliteRoute = "SqfliteRoute"; class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ RaisedButton( onPressed: (){ Navigator.of(context).pushNamed(sqfliteRoute); }, child: Text("sqflite",style: TextStyle(fontSize: 18),), ) ], ), )// This trailing comma makes auto-formatting nicer for build methods. ); } }
跑起來就好,可以好好繼續研究了
最后我要感謝讓我脫離苦海的
https://www.jianshu.com/p/c94326208c27