How to store the image in Sqlite, we know how to store text in Sqlite. In this post, we will learn how to store images in an SQLite database.
Before start, Learn SQFlite CRUD operation in Flutter
Here we are storing images as String in SQLite Database.
Let's get started.
Step 1: Create a Flutter Application
Step 2: Add required dependencies in pubspec.yaml file
dependencies:
image_picker:
sqflite:
path_provider:
|
Step 3: Create a Utility class which will handle the Image fetch and convert as String and vice versa
class Utility {
static Image imageFromBase64String(String base64String) {
return Image.memory(
base64Decode(base64String),
fit: BoxFit.fill,
);
}
static Uint8List dataFromBase64String(String base64String) {
return base64Decode(base64String);
}
static String base64String(Uint8List data) {
return base64Encode(data);
}
}
|
Step 4: Create a Model class to maintain the data class
class Photo {
int id;
String photo_name;
Photo(this.id, this.photo_name);
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
'id': id,
'photo_name': photo_name,
};
return map;
}
Photo.fromMap(Map<String, dynamic> map) {
id = map['id'];
photo_name = map['photo_name'];
}
}
|
Step 5: Now it's time to create a Database. Here we are creating a database name as photos.db.
Let's create a class which will handle all DB Operations
class DBHelper {
static Database _db;
static const String ID = 'id';
static const String NAME = 'photo_name';
static const String TABLE = 'PhotosTable';
static const String DB_NAME = 'photos.db';
Future<Database> get db async {
if (null != _db) {
return _db;
}
_db = await initDb();
return _db;
}
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, DB_NAME);
var db = await openDatabase(path, version: 1, onCreate: _onCreate);
return db;
}
_onCreate(Database db, int version) async {
await db.execute("CREATE TABLE $TABLE ($ID INTEGER, $NAME TEXT)");
}
Future<Photo> save(Photo employee) async {
var dbClient = await db;
employee.id = await dbClient.insert(TABLE, employee.toMap());
return employee;
}
Future<List<Photo>> getPhotos() async {
var dbClient = await db;
List<Map> maps = await dbClient.query(TABLE, columns: [ID, NAME]);
List<Photo> employees = [];
if (maps.length > 0) {
for (int i = 0; i < maps.length; i++) {
employees.add(Photo.fromMap(maps[i]));
}
}
return employees;
}
Future close() async {
var dbClient = await db;
dbClient.close();
}
}
|
Step 6: Now we reached the final step, Create a class to fetch the Images from Gallery and save them to the SQLite database.
here to fetch the Images from Gallery we used image_picker library.
The logic to fetch the Image from the gallery is
pickImageFromGallery() {
ImagePicker.pickImage(source: ImageSource.gallery).then((imgFile) {
String imgString = Utility.base64String(imgFile.readAsBytesSync());
Photo photo = Photo(0, imgString);
dbHelper.save(photo);
refreshImages();
});
}
|
After saving the images in SQLite Database, we are fetching the Images data from Database and showing those images on the screen inside GrideView.
Our SaveImageinDb class contains the below code
class SaveImageDemoSQLite extends StatefulWidget {
//
SaveImageDemoSQLite() : super();
final String title = "Flutter Save Image";
@override
_SaveImageDemoSQLiteState createState() => _SaveImageDemoSQLiteState();
}
class _SaveImageDemoSQLiteState extends State<SaveImageDemoSQLite> {
//
Future<File> imageFile;
Image image;
DBHelper dbHelper;
List<Photo> images;
@override
void initState() {
super.initState();
images = [];
dbHelper = DBHelper();
refreshImages();
}
refreshImages() {
dbHelper.getPhotos().then((imgs) {
setState(() {
images.clear();
images.addAll(imgs);
});
});
}
pickImageFromGallery() {
ImagePicker.pickImage(source: ImageSource.gallery).then((imgFile) {
String imgString = Utility.base64String(imgFile.readAsBytesSync());
Photo photo = Photo(0, imgString);
dbHelper.save(photo);
refreshImages();
});
}
gridView() {
return Padding(
padding: EdgeInsets.all(5.0),
child: GridView.count(
crossAxisCount: 2,
childAspectRatio: 1.0,
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
children: images.map((photo) {
return Utility.imageFromBase64String(photo.photo_name);
}).toList(),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.green,
title: Text(widget.title),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () {
pickImageFromGallery();
},
)
],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Flexible(
child: gridView(),
)
],
),
),
);
}
}
|
Related Topics: Convert BASE64 string to Image in Flutter
Flutter Consume data with HTTP Get and HTTP Post
Article Contributed By :
|
|
|
|
12698 Views |