Local Database in Flutter
Lets see how to save an record inside database and display it in an ListView.
so the first step is to call the sqflite dependency in the pubspec.yaml
sqflite: ^2.0.2
So next we have to create a model class which holds the data to be saved. I am going to save three values so i am naming it as heading, title and link
class Favourite {
final String heading;
final String title;
final String link;
const Favourite({required this.heading, required this.title, required this.link});
factory Favourite.fromJson(Map<String,dynamic> json) => Favourite(
heading: json['heading'],
title: json['title'],
link: json['link']
);
Map<String,dynamic> toJson() =>
{
'heading': heading,
'title': title,
'link': link
};
}
So i am saving in the form of json so i added toJson method and for getting data i added fromJson method as seen above.
So after that i am going to create a DatabaseHelper class file which contain database creation, insertion and retrieval. So i will explain line by line after i will paste the complete code of it.
static int version = 1;
static String dbname = "articles.db";
we are declaring version as 1 and database name as articles.db. Next we have to create a table named fav inside database with the following fields that we have in Favourite class below method tells how to create a table with following fields.
static Future<Database> _getDatabase() async {
return openDatabase(join(await getDatabasesPath(), dbname),
onCreate: (db, version) async =>
await db.execute("CREATE TABLE fav(heading TEXT NOT NULL, title TEXT NOT NULL, link TEXT NOT NULL);"),
version: version
);
}
Next lets see how to insert
static Future<int> saveData(Favourite fav) async {
final db = await _getDatabase();
return db.insert("fav",
fav.toJson(),
conflictAlgorithm: ConflictAlgorithm.replace
);
}
Method to fetch data from database
static Future<List<Favourite>?> getSavedValues() async {
final db = await _getDatabase();
final List<Map<String,dynamic>> maps = await db.query("fav");
if(maps.isEmpty) {
return null;
}
return List.generate(maps.length, (index) => Favourite.fromJson(maps[index]));
}
So entire code for DatabaseHelper is pasted below
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:untitled/models/Favourite_content.dart';
class DatabaseHelper {
static int version = 1;
static String dbname = "articles.db";
static Future<Database> _getDatabase() async {
return openDatabase(join(await getDatabasesPath(), dbname),
onCreate: (db, version) async =>
await db.execute("CREATE TABLE fav(heading TEXT NOT NULL, title TEXT NOT NULL, link TEXT NOT NULL);"),
version: version
);
}
static Future<int> saveData(Favourite fav) async {
final db = await _getDatabase();
return db.insert("fav",
fav.toJson(),
conflictAlgorithm: ConflictAlgorithm.replace
);
}
static Future<List<Favourite>?> getSavedValues() async {
final db = await _getDatabase();
final List<Map<String,dynamic>> maps = await db.query("fav");
if(maps.isEmpty) {
return null;
}
return List.generate(maps.length, (index) => Favourite.fromJson(maps[index]));
}
}
Lets see insert line from main.dart file
saveData(Favourite(heading: title, title: subtitle, link: url));void saveData(Favourite fav) async {
await DatabaseHelper.saveData(fav);
}
Full file for saving and fetching . And for fetching data from database getSavedData() method and for saving data we call saveData() method
import 'package:flutter/material.dart';
import 'package:untitled/helper/DatabaseHelper.dart';
import 'package:untitled/models/Favourite_content.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:share_plus/share_plus.dart';
class ReadContentPage extends StatefulWidget {
String title;
String url;
String subtitle;
ReadContentPage(this.title, this.subtitle, this.url);
@override
State<ReadContentPage> createState() => _ReadContentPageState(title, subtitle, url);
}
class _ReadContentPageState extends State<ReadContentPage> {
String title;
String url;
String subtitle;
int _indexView = 1;
bool saved = false;
List<Favourite>? items = []; _ReadContentPageState(this.title, this.subtitle, this.url);
void saveData(Favourite fav) async {
await DatabaseHelper.saveData(fav);
} Future<List<Favourite>?> getSavedData() async {
items = await DatabaseHelper.getSavedValues();
for(var fav in items!) {
print(fav.title);
}
}
@override
void initState() {
super.initState();
getSavedData();
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text(title, maxLines: 2,
style: const TextStyle(fontFamily: 'sanss',
fontSize: 19, color: Colors.white,)
),
actions: [
IconButton(
onPressed: () {
saveData(Favourite(heading: title, title: subtitle, link: url));
setState(() {
saved = !saved;
});
},
icon: saved ? Icon(Icons.favorite_outlined) : Icon(Icons.favorite_border)
)
],
)) ,
);
}
}