Storing thumnail to SqlLite from Flutter App - sqlite

Here i want to store the thumbnail to My database which is sqlite, and i am not able to store it. i am able to store it in local directory but. i wana call it from my data model. please help
Here is my Code.
_getThumb(videoPathUrl) async {
var appDocDir = await getApplicationDocumentsDirectory();
final folderPath = appDocDir.path;
print(folderPath);
String thumb = await Thumbnails.getThumbnail(
thumbnailFolder: folderPath,
videoFile: videoPathUrl,
imageType: ThumbFormat.JPEG,
quality: 25,
);
print('thumbnail: $thumb');
return thumb = model.thumbnail;
}
}

I Have Found a Solution "the Problem is not with the plugin or the method it adopts to store the Image" The problem is that it is not clear that how should a Unit8List is to be stored in the database.
In My case. __
I am Using this code to Store the Image.
_getThumb(videoPathUrl) async {
final thumb = await VideoThumbnail.thumbnailData(
video: videoPathUrl,
imageFormat: ImageFormat.JPEG,
maxWidth: 100,
maxHeight: 100,
quality: 75,
);
}
Then I am Using this final thumb to be saved against my VideoModel Variable of thumbnail
_getThumb(videoPathUrl) async {
final thumb = await VideoThumbnail.thumbnailData(
video: videoPathUrl,
imageFormat: ImageFormat.JPEG,
maxWidth: 100,
maxHeight: 100,
quality: 75,
);
print('thumbnail $thumb'); //Add these lines
model.thumbnail = thumb; //Add these Lines
return thumb; //Add these lines
}
And Once i have saved it i can see the print result in my debug console. Once i have that i am sure that it is saved.
Now i have to save it as a Blob in my db not as a String.
and thumbnail should be a Unit8List variable not a String Variable.
See the example
and in database
I am Also adding the full Video Model and DbHelper files for Others to use.
VideoModel.dart
import 'dart:typed_data';
import 'model.dart';
class VideoModel extends Model {
static String table = 'videos';
int id;
String videoName;
String video;
Uint8List thumbnail;
VideoModel({
this.id,
this.videoName,
this.video,
this.thumbnail,
});
static VideoModel fromMap(Map<String, dynamic> map) {
return VideoModel(
id: map["id"],
videoName: map['videoName'].toString(),
video: map['video'],
thumbnail: map['thumbnail'],
);
}
Map<String, dynamic> toMap() {
Map<String, dynamic> map = {
'id': id,
'videoName': videoName,
'video': video,
'thumbnail': thumbnail,
};
if (id != null) {
map['id'] = id;
}
return map;
}
}
DbHelper.dart
abstract class DB {
static Database _db;
static int get _version => 1;
static Future<void> init() async {
if (_db != null) {
return;
}
try {
var databasesPath = await getDatabasesPath();
String _path = p.join(databasesPath, 'video.db');
_db = await openDatabase(_path, version: _version, onCreate: onCreate);
} catch (ex) {
print(ex);
}
}
static void onCreate(Database db, int version) async {
await db.execute(
'CREATE TABLE videos (id INTEGER PRIMARY KEY AUTOINCREMENT, videoName STRING, video STRING, thumbnail BLOB)');
}
static Future<List<Map<String, dynamic>>> query(String table) async =>
_db.query(table);
static Future<int> insert(String table, Model model) async =>
await _db.insert(table, model.toMap());
static Future<int> update(String table, Model model) async => await _db
.update(table, model.toMap(), where: 'id = ?', whereArgs: [model.id]);
static Future<int> delete(String table, Model model) async =>
await _db.delete(table, where: 'id = ?', whereArgs: [model.id]);
static Future<Batch> batch() async => _db.batch();
}
Now when you have done these edits You can just all your image using
Image.memory(add your Image Here);
see example:
I hope that this will help some of you if you need help Let me know. Thanks

Related

Is there a NoSQL alternative to SQLite for flutter?

I am building a standalone(no API calls to MongoDB or Firebase etc.) flutter app for which database management is crucial. Currently, I am storing it as JSON, but it's simply inefficient. I cannot use SQLite because the data are very nested, in fact, JSON is the only way to store my data. So, I am looking for a NoSQL alternative.
This is the data model I want to store.
lib/book_model.dart
#JsonSerializable()
class Book {
/// Do not change this. It's a primary key.
String bookLink;
String authors = null;
String thumbnail = null;
String bookName = null;
List<Chapter> totalChaptersList = [];
///todo: determine datatype
var currentChapter;
String summary = null;
double rating = 0.0;
List<String> genres = [];
Book({
this.bookLink,
this.authors,
this.thumbnail,
this.bookName,
this.totalChaptersList,
this.currentChapter,
this.summary,
this.rating,
this.genres,
});
Book.generateFromSearchBook(SearchBook searchBook) {
this.authors = searchBook.authors;
this.bookLink = searchBook.bookLink;
this.bookName = searchBook.bookName;
this.thumbnail = searchBook.thumbnail;
}
// #override
// String toString() {
// return "<$bookLink , $authors , $thumbnail , $bookName , $summary , $genres , $rating , $totalChaptersList , $currentChapter>";
// }
factory Book.fromJson(Map<String, dynamic> json) => _$BookFromJson(json);
Map<String, dynamic> toJson() => _$BookToJson(this);
}
#JsonSerializable()
class Chapter {
String name = null;
String date = null;
String chapterLink = null;
#JsonKey(defaultValue: false)
bool has_read = false;
List<Page> pages = [];
Chapter({
this.name,
this.date,
this.chapterLink,
this.has_read,
this.pages,
});
// #override
// String toString() {
// return "<$name , $date , $chapterLink , $has_read , $pages>";
// }
factory Chapter.fromJson(Map<String, dynamic> json) => _$ChapterFromJson(json);
Map<String, dynamic> toJson() => _$ChapterToJson(this);
}
#JsonSerializable()
class Page {
String pageLink = null;
int pageNumber = 0;
Page({
this.pageLink,
this.pageNumber,
});
// #override
// String toString() {
// return "<$pageLink , $pageNumber>";
// }
factory Page.fromJson(Map<String, dynamic> json) => _$PageFromJson(json);
Map<String, dynamic> toJson() => _$PageToJson(this);
}
I found these two
Hive - Hive is a lightweight and blazing fast key-value database written in pure Dart. Inspired by Bitcask.
ObjectBox - ObjectBox is a super-fast database storing Dart objects locally.
I use Hive. It's fast and easy to use.you can use hive_generator with json_serializable and freezed to create a HiveObject class.
example:
#HiveType(typeId: 0)
class Person extends HiveObject {
#HiveField(0)
String name;
#HiveField(1)
int age;
}
You can also use hive_box to turn your hive box into a listenable and listen to database changes.
example:
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
class SettingsPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: Hive.box('settings').listenable(),
builder: (context, box, widget) {
return Switch(
value: box.get('darkMode'),
onChanged: (val) {
box.put('darkMode', val);
}
);
},
);
}
}

Flutter Web & Firebase - Store/log information recieved from a JSON API

I would like to log/store the data received from a JSON API to Firebase as soon as the visitor accesses my website. There are no user accounts. The API returns something akin to this -only 1 post. I have implemented the data model using a JSON to Dart converter but I am confused about how to parse( figured how to retrieve it using HTTP) the JSON and store it in Firebase.
Here is the example model for reference.
import "dart:convert";
import "package:http/http.dart";
import "package: website/user.dar";
class Post {
int userId;
int id;
String title;
String body;
Post({this.userId, this.id, this.title, this.body});
Post.fromJson(Map<String, dynamic> json) {
userId = json['userId'];
id = json['id'];
title = json['title'];
body = json['body'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['userId'] = this.userId;
data['id'] = this.id;
data['title'] = this.title;
data['body'] = this.body;
return data;
}
}
class HTTP
I have already successfully set up Firebase Analytics. Currently not using any other firebase packages.
Update: Figured out how to read JSON in Dart.
import 'dart:convert';
import 'http:http.dart';
class HttpService {
static Future<IPLocation> getLocation() async {
Response response = await get(
"http://jsonplaceholder.typicode.com/posts/1");
if (response.statusCode == 200) {
final body = jsonDecode(response.body);
Post post = IPLocation.fromJson(body);
return post;
} else {
throw Exception("Failed to load Post. StatusCode: ${response.statusCode}");
}
}
}
Now the question remains - what is the best way to store this in Firebase? I would like to map them to each visitor- but I cannot set up user accounts.
Not sure if this is what you're looking for because I never used Firebase, but this is what I used to use to extract data from MySQL.
import 'dart:convert';
List<Listings> listingsFromJson(String str) =>
List<Listings>.from(json.decode(str).map((x) => Listings.fromJson(x)));
String listingsToJson(List<Listings> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Listings{
Listings({
this.customerId,
this.image,
this.website,
});
String customerId;
String image;
String website;
factory Listing.fromJson(Map<String, dynamic> json) => Listings(
customerId: json["customer_id"],
image: json["image"],
website: json["website"],
);
Map<String, dynamic> toJson() => {
"customer_id": customerId,
"image": image,
"website": website,
};
}
Read Fetch and Read JSON input.
Here for clarity
import "dart:convert";
import "package:http/http.dart";
import "package: website/user.dar";
class Post {
int userId;
int id;
String title;
String body;
Post({this.userId, this.id, this.title, this.body});
Post.fromJson(Map<String, dynamic> json) {
userId = json['userId'];
id = json['id'];
title = json['title'];
body = json['body'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['userId'] = this.userId;
data['id'] = this.id;
data['title'] = this.title;
data['body'] = this.body;
return data;
}
}
Firebase
Look at setting up Anonymous users using FirebaseAuth. Then set up and log userProperties.

Flutter: SQLite database in external storage. database is null

I am writing an app to store some events and dates at which events happened (For history students as part of a project). I wish to create an SQLite database, stored in some preferred location in my device. Later I want this database to merge with main database using computer. Here is my database helper class;
class DatabaseHelper {
static final _dbName = 'mainDatabase.db';
static final _dbVersion = 1;
static final _mainTable = 'mainTable';
static final _storyTable = 'storyTable';
static final _topicTable = 'topicTable';
static final columnId = '_id';
static final title = 'title';
static final description = 'description';
static final parentId = 'topic_id';
static final priority = 'priority';
static final iconId = 'iconId';
static final futureImage = 'image';
static final year = 'year';
static final month = 'month';
static final day = 'day';
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database _database;
Future<Database> get database async {
if (_database != null) {
return _database;
}
_database = await _checkPermission();
return _database;
}
var status;
_checkPermission() async {
this.status = await Permission.storage.status;
debugPrint(' storage permission status : ${this.status}');
if (await Permission.storage.request().isGranted) {
_initiateDatabase();
} else if (await Permission.storage.request().isUndetermined) {
debugPrint('Undetermined permission');
} else if (await Permission.storage.request().isDenied) {
debugPrint('Permission denied');
_checkPermission();
} else if (await Permission.storage.request().isPermanentlyDenied) {
debugPrint(' it has been permenantly denied');
}
}
_initiateDatabase() async {
debugPrint(' database initialized');
Directory directory = await getExternalStorageDirectory();
String path = join(directory.path, _dbName);
debugPrint('Path for database: ${path}');
return await openDatabase(path, version: _dbVersion, onCreate: _onCreate);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE $_mainTable (
$columnId INTEGER NOT NULL,
$year INTEGER,
$month INTEGER,
$day INTEGER,
$title TEXT NOT NULL,
$description TEXT,
$priority INTEGER,
$parentId INTEGER,
PRIMARY KEY($columnId AUTOINCREMENT)
);
'''); /
Future<int> insertEvent(Map<String, dynamic> row) async {
Database db = await instance.database;
debugPrint(' event : ${row}');
assert(db != null); //Issue!!!!
return await db.insert(_mainTable, row);
}
}
My code may seem messy, because I am not from this background. I apologize for that.
When I tried to add an event I get this error;
I/flutter ( 8090): event id is null
I/flutter ( 8090): storage permission status : PermissionStatus.granted
I/flutter ( 8090): database initialized
I/flutter ( 8090): event : {year: null, month: null, day: null, title: adsfasdf, description: null, priority: 0, topic_id: null}
E/flutter ( 8090): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: 'package:thisDay/config/databaseHelper.dart': Failed assertion: line 189 pos 12: 'db != null': is not true.
/////////////// some code
E/flutter ( 8090):
I/flutter ( 8090): Path for database: /storage/emulated/0/Android/data/com.example.thisDay/files/mainDatabase.db
What should I do? I am stuck at this point. I have my db file at /storage/emulated/0/Android/data/com.example.thisDay/files/mainDatabase.db . But can't add anything in it.
Any help would be greately appreciated.
Nb:- At first I used getApplicationDirectory instead of External directory. There were no issues. I have to switch because of portability issues
Finally, I fixed my issue by myself. _initializeDatabase() has a return type Future<Database>. So making respective changes on code fixed my issue.
Future<Database> _checkPermission() async {
this.status = await Permission.storage.status;
debugPrint(' storage permission status : ${this.status}');
if (await Permission.storage.request().isGranted) {
return await _initiateDatabase();
} else if (await Permission.storage.request().isUndetermined) {
debugPrint('Undetermined permission');
} else if (await Permission.storage.request().isDenied) {
debugPrint('Permission denied');
_checkPermission();
} else if (await Permission.storage.request().isPermanentlyDenied) {
debugPrint(' it has been permenantly denied');
}
}
Future<Database> _initiateDatabase() async {
debugPrint(' database initialized');
Directory directory = await getExternalStorageDirectory();
String path = join(directory.path, _dbName);
debugPrint('Path for database: ${path}');
return await openDatabase(path, version: _dbVersion, onCreate: _onCreate);
}
for creating a database and table you can refer this code
Database database;
opendatabase() async {
// Delete the database
String databasesPath = await getDatabasesPath();
String path = join(databasesPath, "sample.db");
// await deleteDatabase(path);
database = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
// When creating the db, create the table
await db.execute(
'CREATE TABLE tbl_test (id INTEGER PRIMARY KEY, sample TEXT, code TEXT, format TEXT)',
);
});
}

how to display a custom list data on the app page in flutter

1[https://i.stack.imgur.com/yI2Cp.png">]1
i have tried this code to retrieve data from subcollection of the same name(userProducts) stored in many firebase documents.How do i display this data in a container on the app page ? I tried using listiew.builder but it doesnt work.
The first function
static List<products> finalProductsList = [] ;
productsList() async
{
List list_of_products = await Firestore.instance.collection("products")
.getDocuments()
.then((val) => val.documents);
for (int i=0; i<list_of_products.length; i++)
{
Firestore.instance.collection("products").document(
list_of_products[i].documentID.toString()).collection("userProducts").snapshots().listen(CreateListofProducts);
}
}
Second function
CreateListofProducts(QuerySnapshot snapshot)async
{
var docs = snapshot.documents;
for (var Doc in docs)
{
finalProductsList.add(products.fromFireStore(Doc));
}
}
CourseModel
class products {
final String prodId;
final String ownerId;
final String username;
final String price;
final String productname;
final String details;
final String color;
final String composition;
final String washandcare;
final String sizeandfit;
final String shopmediaUrl;
final String id;
final dynamic likes;
products({ this.prodId,
this.ownerId,
this.username,
this.price,
this.details,
this.productname,
this.color,
this.composition,
this.washandcare,
this.sizeandfit,
this.shopmediaUrl,
this.id,
this.likes,});
factory products.fromFireStore(DocumentSnapshot doc)
{
Map data = doc.data ;
return products(
prodId: doc['prodId'],
ownerId: doc['ownerId'],
username: doc['username'],
price: doc['price'],
productname: doc['productname'],
details: doc['details'],
shopmediaUrl: doc['shopmediaUrl'],
color:doc['color'],
composition:doc['composition'],
washandcare:doc['washandcare'],
sizeandfit:doc['sizeandfit'],
likes: doc['likes'],
);
SO if i understand you, you want to get data on multiple collections on multiple documents?
If so... you should use collecionGroup, you can learn how to use here, make sure to adjust your firestore rules.

Escalate DBProvider Flutter

I am new to working with databases in flutter. I have a data folder with a database.dart in the following form. This is fine for one table and with a few CRUD functions such as newNote or getNotes, but what happens when you have multiple tables and multiple CRUD Functions? Are you supposed to dump them all on this database.dart file making it chaotic? What are better alternatives for organization?
class DBProvider {
DBProvider._();
static final DBProvider db = DBProvider._();
Database _database;
Future<Database> get database async {
if (_database != null) {
return _database;
}
_database = await initDB();
return _database;
}
initDB() async {
Directory documentsDir = await getApplicationDocumentsDirectory();
String path = join(documentsDir.path, 'app.db');
return await openDatabase(path, version: 1, onOpen: (db) async {
}, onCreate: (Database db, int version) async {
// Create the note table
await db.execute('''
CREATE TABLE note(
id INTEGER PRIMARY KEY,
contents TEXT DEFAULT ''
)
''');
});
}
newNote(Note note) async {
final db = await database;
var res = await db.insert('note', note.toJson());
return res;
}
}

Resources