Updated 25 April 2023
In this blog, we are going to learn how we can Store data in Sqlite in flutter.
If you are creating an app that needs to store data in a database instead of a local file or key-value then use Sqlite.
In general, databases provide faster inserts, updates, and queries compared to other local persistence solutions.
Flutter apps can make use of SQLite databases via the sqflite
plugin available on pub.dev.
Looking for the best Flutter app development?
First, you need to add the sqflite
package to your pubspec.yaml
file and run flutter pub get
to install it.
1 2 |
dependencies: sqflite: ^2.0.0+3 |
1 2 |
import 'package:sqflite/sqflite.dart'; import 'package:path/path.dart'; |
Create a class for your database and define the tables and columns you want to use:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
class DbManager { Database? _database = null; Future openDb() async { _database = await openDatabase(join(await getDatabasesPath(), "sqliteExample.db"), version: 1, onCreate: (Database db, int version) async { await db.execute( "CREATE TABLE person (id INTEGER PRIMARY KEY autoincrement, name TEXT, age TEXT)", ); }); return _database; } Future<int?> insertData(Model model) async { await openDb(); int? a= await _database?.insert('person', model.toJson()); return a; } Future<List<Model>> getDataList() async { await openDb(); final List<Map<String, dynamic>> maps = await _database!.rawQuery('SELECT * FROM person'); return List.generate(maps.length, (i) { return Model( id: maps[i]['id'], personName: maps[i]['name'], age: maps[i]['age']); }); } Future<int> updateData(Model model) async { await openDb(); return await _database!.update('person', model.toJson(), where: "id = ?", whereArgs: [model.id]); } Future<void> deleteData(Model model) async { await openDb(); await _database!.delete('person', where: "id = ?", whereArgs: [model.id]); } } |
In this example, we have created a table named “Person” with columns: “name”, and “age”.
Use the DbManager instance to perform operations on the database, such as inserting data, querying, updating, and deleting data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Model { int? id; String? personName; String? age; Model({this.id, this.personName, this.age}); Model fromJson(json) { return Model( id: json['id'], personName: json['name'], age: json['"age"']); } Map<String, dynamic> toJson() { return {'name': personName, 'age': age}; } } |
Check the below code to insert data in Sqlite Database by the user interface.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 |
class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { final DbManager dbManager = new DbManager(); Model? model; List<Model>? modelList; TextEditingController nameTextController = TextEditingController(); TextEditingController ageTextController = TextEditingController(); @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Sqlite DB In Flutter'), ), floatingActionButton: FloatingActionButton( onPressed: () { showDialog( context: context, builder: (context) { return DialogBox().dialog( context: context, onPressed: () async{ Model model = new Model( personName: nameTextController.text, age: ageTextController.text); int? id = await dbManager.insertData(model) ; print("data inserted ${id}" ); WidgetsBinding.instance.addPostFrameCallback((_){ setState(() { nameTextController.text = ""; ageTextController.text = ""; }); Navigator.of(context).pop(); }); }, textEditingController1: nameTextController, textEditingController2: ageTextController, /* nameTextFocusNode: nameTextFocusNode, ageTextFocusNode: ageTextFocusNode,*/ ); }); }, child: Icon( Icons.add, color: Colors.white, ), ), body: FutureBuilder( future: dbManager.getDataList(), builder: (context, snapshot) { if (snapshot.hasData) { modelList = snapshot.data as List<Model>?; return ListView.builder( itemCount: modelList?.length, itemBuilder: (context, index) { Model _model = modelList![index]; return ItemCard( model: _model, nameTextController: nameTextController, ageTextController: ageTextController, onDeletePress: () { dbManager.deleteData(_model); WidgetsBinding.instance.addPostFrameCallback((_){ setState(() {}); }); }, onEditPress: () { nameTextController.text = _model.personName??""; ageTextController.text = _model.age??""; showDialog( context: context, builder: (context) { return DialogBox().dialog( context: context, onPressed: () { Model __model = Model( id: _model.id, personName: nameTextController.text, age: ageTextController.text); dbManager.updateData(__model); WidgetsBinding.instance.addPostFrameCallback((_){ setState(() { nameTextController.text = ""; ageTextController.text = ""; }); }); Navigator.of(context).pop(); }, textEditingController2: ageTextController, textEditingController1: nameTextController); }); }, ); }, ); } return Center( child: CircularProgressIndicator(), ); }, ), ); } } class DialogBox { Widget dialog( {BuildContext? context, Function? onPressed, TextEditingController? textEditingController1, TextEditingController? textEditingController2, /*FocusNode? nameTextFocusNode, FocusNode? ageTextFocusNode*/}) { return AlertDialog( title: Text("Enter person Data"), content: Container( height: 100, child: Column( children: [ TextFormField( controller: textEditingController1, keyboardType: TextInputType.text, // focusNode: nameTextFocusNode, decoration: InputDecoration(hintText: "Enter person name "), /*autofocus: true,*/ onFieldSubmitted: (value) { //nameTextFocusNode?.unfocus(); //FocusScope.of(context!).requestFocus(ageTextFocusNode); }, ), TextFormField( controller: textEditingController2, keyboardType: TextInputType.number, //focusNode: ageTextFocusNode, decoration: InputDecoration(hintText: "enter person age"), onFieldSubmitted: (value) { // ageTextFocusNode?.unfocus(); }, ), ], ), ), actions: [ MaterialButton( onPressed: () { Navigator.of(context!).pop(); }, color: Colors.blue, child: Text( "Cancel", ), ), MaterialButton( onPressed:(){ onPressed!(); } /*onPressed!()*/, child: Text("Save"), color: Colors.blue, ) ], ); } } class ItemCard extends StatefulWidget { Model? model; TextEditingController? nameTextController; TextEditingController? ageTextController; Function? onDeletePress; Function? onEditPress; ItemCard( {this.model, this.nameTextController, this.ageTextController, this.onDeletePress, this.onEditPress}); @override _ItemCardState createState() => _ItemCardState(); } class _ItemCardState extends State<ItemCard> { final DbManager dbManager = new DbManager(); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(8.0), child: Card( child: Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( 'Name: ${widget.model?.personName}', style: TextStyle(fontSize: 15), ), Text( 'age: ${widget.model?.age}', style: TextStyle( fontSize: 15, ), ), ], ), Row( children: [ CircleAvatar( backgroundColor: Colors.white, child: IconButton( onPressed: (){ widget.onEditPress!(); }, icon: Icon( Icons.edit, color: Colors.blueAccent, ), ), ), SizedBox( width: 15, ), CircleAvatar( backgroundColor: Colors.white, child: IconButton( onPressed: (){widget.onDeletePress!();}, icon: Icon( Icons.delete, color: Colors.red, ), ), ) ], ), ], ), ), ), ); } } |
Hope, this post gives you an idea about storing data in Sqlite in Flutter.
To know more please click here.
Thank you !!
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.