Database empty flutter - flutter

I'm getting empty string when I trying to get the titles. Please help me.
Here's my source code
Here's my task.dart file
// task.dart
class Task {
int? id;
String? title;
String? note;
int? isCompleted;
String? date;
String? startTime;
String? endTime;
int? color;
int? remind;
String? repeat;
Task({
this.id,
this.title,
this.note,
this.isCompleted,
this.date,
this.startTime,
this.endTime,
this.color,
this.remind,
this.repeat,
});
Task.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
note = json['note'];
isCompleted = json['isCompleted'];
date = json['date'];
startTime = json['startTime'];
endTime = json['endTime'];
color = json['color'];
remind = json['remind'];
repeat = json['repeat'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic> ();
data['id'] = this.id;
data['title'] = this.title;
data['note'] = this.note;
data['isCompleted'] = this.isCompleted;
data['date'] = this.date;
data['startTime'] = this.startTime;
data['endTime'] = this.endTime;
data['color'] = this.color;
data['remind'] = this.remind;
data['repeat'] = this.repeat;
return data;
}
}
Here's my task_controller.dart file
import 'package:calendar_app/db/db_helper.dart';
import 'package:calendar_app/models/task.dart';
import 'package:get/get.dart';
// task_controller.dart
class TaskController extends GetxController {
#override
void onReady() {
getTasks();
super.onReady();
}
var taskList = <Task>[].obs;
Future<int> addTask({Task? task}) async{
return await DBHelper.insert(task);
}
void getTasks() async {
List<Map<String, dynamic>> tasks = await DBHelper.query();
taskList.assignAll(tasks.map((data) => new Task.fromJson(data)).toList());
}
}
db_helper.dart
import 'package:calendar_app/models/task.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart';
import 'dart:developer' as devtools show log;
// db_helper.dart
class DBHelper {
static Database? _db;
static final int _version = 1;
static final String _tableName = 'Tasks';
static Future<void> initDb() async {
if (_db != null) {
return;
}
try {
String _path = await getDatabasesPath() + 'tasks.db';
_db = await openDatabase(
_path,
version: _version,
onCreate: (db, version) {
devtools.log('Creating a new one');
return db.execute(
"CREATE TABLE $_tableName("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"title STRING, note TEXT, date STRING, "
"startTime STRING, endTime STRING, "
"remind INTEGER, repeat STRING, "
"color INTEGER, "
"isCompleted INTEGER)",
);
},
);
} catch (e) {
devtools.log(e.toString());
}
}
static Future<int> insert(Task? task) async {
devtools.log('Insert func called');
return await _db?.insert(_tableName, task!.toJson()) ?? 1;
}
static Future<List<Map<String, dynamic>>> query() async {
devtools.log('Query func called');
return await _db!.query(_tableName);
}
}
When I trying to get a print statement of title it return empty. I have no idea what's happening here. Please help me.
print(_taskController.taskList[index].note.toString());
I'm following dbstech tutorial. If anyone have the source code please let me know.

First in getTask function try to reset taskList by calling this:
void getTasks() async {
taskList = []; // <--- add this
List<Map<String, dynamic>> tasks = await DBHelper.query();
taskList.assignAll(tasks.map((data) => new Task.fromJson(data)).toList());
}
Then I think you issue is your table is empty. After run your code try add something to your table then print it and see the result.

Related

Flutter error : The argument type 'Map<dynamic, dynamic>' can't be assigned to the parameter type 'Map<String, dynamic>'

I am trying to store the image in SQFLite database as string. While setting up the DBHelper class, I am getting the said error.
Here is the code of model.dart and dbhelper.dart
class Photo {
int? id;
String? photoName;
Photo({this.id, this.photoName});
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
'id': id,
'photoName': photoName,
};
return map;
}
Photo.fromMap(Map<String, dynamic> map) {
id = map['id'];
photoName = map['photoName'];
}
}
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'model.dart';
import 'dart:io' as io;
import 'dart:async';
class DBHelper {
static Database? _db;
static const String ID = 'id';
static const String NAME = 'photoName';
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 photo) async {
var dbClient = await db;
photo.id = await dbClient!.insert(TABLE, photo.toMap());
return photo;
}
Future<List<Photo>> getPhotos() async {
var dbClient = await db;
List<Map> maps = await dbClient!.query(TABLE, columns: [ID, NAME]);
List<Photo> photos = [];
if (maps.length > 0) {
for (int i = 0; i < maps.length; i++) {
photos.add(Photo.fromMap(maps[i])); // ==> Here, at maps[i], it shows the error
}
}
return photos;
}
Future close() async {
var dbClient = await db;
dbClient!.close();
}
}
How can I solve this ?
Change your Photo model to Map<dynamic, dynamic>. The reason for this is that the db is returning a Map<dynamic, dynamic>.
class Photo {
int? id;
String? photoName;
Photo({this.id, this.photoName});
Map<dynamic, dynamic> toMap() {
var map = <String, dynamic>{
'id': id,
'photoName': photoName,
};
return map;
}
Photo.fromMap(Map<dynamic, dynamic> map) {
id = map['id'];
photoName = map['photoName'];
}
}

How to get individual column value from sqflite database flutter

// THis is model>>
class CompanyProfile {
// to create name tag for database
static const String columnId = '_id';
static const String comapnyNametag = 'CompanyName';
static const String phoneNumbertag = 'PhoneNumber';
static const String addressLine1tag = 'AddressLine1';
static const String addressLine2tag = 'AddressLine2';
static const String emailaddresstag = 'EmailAddress';
static const String invPrefixtag = 'InvoicePrefix';
static const String footerTexttag = 'FooterText';
// to create new Profile or Update profile
int? id;
String? companyName;
String? addressLine1;
String? addressLine2;
String? emailAddress;
String? phoneNumber;
String? invPrefix;
String? footerText;
CompanyProfile({
this.id,
this.companyName,
this.addressLine1,
this.addressLine2,
this.emailAddress,
this.phoneNumber,
this.invPrefix,
this.footerText,
});
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
comapnyNametag: companyName,
phoneNumbertag: phoneNumber,
addressLine1tag: addressLine1,
addressLine2tag: addressLine2,
emailaddresstag: emailAddress,
invPrefixtag: invPrefix,
footerTexttag: footerText,
};
if (id != null) {
map[columnId] = id;
}
return map;
}
CompanyProfile.fromMap(Map<String, dynamic> map) {
id = map[columnId];
companyName = map[comapnyNametag];
phoneNumber = map[phoneNumbertag];
addressLine1 = map[addressLine1tag];
addressLine2 = map[addressLine2tag];
emailAddress = map[emailaddresstag];
invPrefix = map[invPrefixtag];
footerText = map[footerTexttag];
}
}
//this is databasae helper to create database
import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import '../models/company_profile.dart';
class ProfileProvider {
static const _dbName = 'profile.db';
static const _dbVersion = 1;
static Database? _db;
String tableName = 'profile';
String columnId = '_id';
String comapnyNametag = 'CompanyName';
String phoneNumbertag = 'PhoneNumber';
String addressLine1tag = 'AddressLine1';
String addressLine2tag = 'AddressLine2';
String emailaddresstag = 'EmailAddress';
String invPrefixtag = 'InvoicePrefix';
String footerTexttag = 'FooterText';
ProfileProvider._privateConstructor();
static final ProfileProvider instance = ProfileProvider._privateConstructor();
Future<Database?> get database async {
if (_db != null) return _db;
_db = await _createDB();
return _db;
}
_createDB() async {
Directory dir = await getApplicationDocumentsDirectory();
String path = join(dir.path, _dbName);
return await openDatabase(
path,
version: _dbVersion,
onCreate: _onCreate,
);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
create table $tableName (
$columnId integer primary key autoincrement,
$comapnyNametag text not null,
$phoneNumbertag text not null,
$addressLine1tag text not null,
$addressLine2tag text not null,
$emailaddresstag text not null,
$invPrefixtag text not null,
$footerTexttag text not null
)
''');
}
Future<CompanyProfile> insert(CompanyProfile profile) async {
final db = await database;
profile.id = await db!.insert(tableName, profile.toMap());
return profile;
}
// Future<CompanyProfile> getProfile(int id) async {
// final db = await database;
// final maps = await db.query(
// tableName,
// columns:
// )
// }
// Future<int> insert(Map<String, dynamic> row) async {
// final db = await database;
// return await db!.insert(tableName, row);
// }
Future<List<Map<String, dynamic>>> queryAllRows() async {
final db = await database;
return await db!.query(tableName);
}
// Future<List<CompanyProfile>> profiledetails() async {
// final db = await database;
// final List<Map<String, dynamic>> maps =
// db!.query(tableName) as List<Map<String, dynamic>>;
// return List.generate(maps.length, (i) {
// return CompanyProfile(
// id: maps[i][columnId],
// companyName: maps[i][comapnyNametag],
// phoneNumber: maps[i][phoneNumbertag],
// addressLine1: maps[i][addressLine1tag],
// addressLine2: maps[i][addressLine2tag],
// emailAddress: maps[i][emailaddresstag],
// invPrefix: maps[i][invPrefixtag],
// footerText: maps[i][footerTexttag],
// );
// });
// }
Future<Iterable<CompanyProfile>> getProfile() async {
final db = await database;
final List<Map<String, Object?>> queryResult = await db!.query(tableName);
return queryResult.map((e) => CompanyProfile.fromMap(e));
}
Future<int> update(Map<String, dynamic> row) async {
final db = await database;
int id = row[columnId];
return await db!
.update(tableName, row, where: '$columnId = ?', whereArgs: [id]);
}
Future<int> delete(int id) async {
final db = await database;
return await db!.delete(tableName, where: '$columnId = ?', whereArgs: [id]);
}
}
// this is database helper
Using this model I was able to save data in the database.
//From debug Console.
{_id: 1, CompanyName: a, PhoneNumber: a, AddressLine1: a, AddressLine2: a, EmailAddress: a, InvoicePrefix: a, FooterText: a}
Now I Want to get the values and show in a profile screen like this:
Company Name: a
Address: addressline1 and address line 2
Phone: a
Email: a
Invoice Prefix: a
Footer Text: a
Later I will make a pdf file using this data as well.
Therefore, I need to get the values individually.
Anybody can help me about this?
I am searching in google and youtube but nothing works. some methods doesn't work becasue very old, and most of the methods shows how to create a list graving values from database. I don't want to create any list. I will have only one data in the whole database and i want use this everywhere in the app.
Lots of talking :p
here you just get one record back as your data model
Future<CompanyProfile> getProfile(int id) async {
final db = await database;
final maps = await db.query(tableName, where: '_id = ?', whereArgs: [id]);
return CompanyProfile.fromMap(maps[0]);
}

I have an error like the non-nullable variable 'sessionUser' must be initialized

I have an error like:
The non-nullable variable 'sessionUser' must be initialized. try adding an initializer expression...
I searched a lot on the net but I did not find a solution to my problem. Can you help me to solve this problem?
import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';
class UserModel {
String id;
String nom;
String email;
UserModel({
required this.id,
required this.nom,
required this.email
});
static UserModel sessionUser;
factory UserModel.fromJson(Map<String,dynamic> i) => UserModel(
id: i['id'],
nom: i['nom'],
email: i['email']
);
Map<String,dynamic> toMap() => {
"id": id,
"nom": nom,
"email": email
};
static void saveUser(UserModel user) async {
SharedPreferences pref = await SharedPreferences.getInstance();
var data = json.encode(user.toMap());
pref.setString("user", data);
pref.commit();
}
static void getUser() async {
SharedPreferences pref = await SharedPreferences.getInstance();
var data = pref.getString("user");
if (data != null) {
var decode = json.decode(data);
var user = await UserModel.fromJson(decode);
sessionUser = user;
} else {
sessionUser = UserModel();
}
}
static void logOut() async {
SharedPreferences p = await SharedPreferences.getInstance();
p.setString("user", null);
sessionUser = null;
p.commit();
}
}
your variable sessionUser is not initialized. Try something like this :
static UserModel? sessionUser;
The ? means the variable can be null, so you'll have to check if the variable is null before using later in your code.

Flutter getting error while inserting values in sqllite

I am trying to insert my data in sqllite
Here is my code
class Cart {
int id;
String title;
String image;
String price;
String color;
String sizeselect;
Cart({
this.id,
this.title,
this.image,
this.price,
this.color,
this.sizeselect,
});
factory Cart.fromJson(Map<String, dynamic> data) => new Cart(
id: data["id"],
title: data["title"],
image: data["image"],
price: data["price"],
color: data["color"],
sizeselect: data["sizeselect"],
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"image": image,
"price": price,
"color": color,
"sizeselect": sizeselect,
};
}
class DatabaseHelper {
static final _databaseName = "MyDatabase.db";
static final _databaseVersion = 1;
static final table = 'my_table';
// make this a singleton class
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
// only have a single app-wide reference to the database
static Database _database;
Future<Database> get database async {
if (_database != null) return _database;
// lazily instantiate the db the first time it is accessed
_database = await _initDatabase();
return _database;
}
// this opens the database (and creates it if it doesn't exist)
_initDatabase() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, _databaseName);
return await openDatabase(path,
version: _databaseVersion,
onCreate: _onCreate);
}
// SQL code to create the database table
Future _onCreate(Database db, int version) async {
await db.execute("CREATE TABLE $table ("
"id INTEGER PRIMARY KEY,"
"title TEXT,"
"image TEXT,"
"color TEXT,"
"price TEXT,"
"sizeselect TEXT"
")");
}
Future<int> insert(cart) async {
print(cart.id);
Database db = await instance.database;
return await db.insert(table, cart);
}
}
I am trying to pass like this
onPressed: () async {
var cart = Cart();
cart.id = widget.product.id;
cart.title = widget.product.title;
cart.image = widget.product.image;
cart.price = widget.product.normalPrice;
cart.color = selectedColor;
cart.sizeselect = selectedSize;
print(cart);
final dbHelper = DatabaseHelper.instance;
final id = await dbHelper.insert(cart);
// Model.createCustomer(map);
}
Its showing this error while passing data type 'Cart' is not a subtype of type 'Map<String, dynamic>'
Can any one please tell i need to convert it to something or what ? I think i need to change the json to String or something ? i just need to insert data in database but on this error i am stuck :/
Edit the line
return await db.insert(table, cart);
With
return await db.insert(table, cart.toJson());
You need to import below third parties
import 'package:path_provider/path_provider.dart';
// path_provider: ^1.6.0
import 'package:sqflite/sqflite.dart';
// sqflite: ^1.3.0
This is DatabaseHelper Class
const String databaseName = "cart.db";
const int databaseVersion = 1;
// ------ CART Table Columns ---------- //
mixin CartTable {
static final String colTitle = "title";
static final String colImage = "image";
static final String colPrice = "price";
static final String colColor = "color";
static final String colSizeSelect = "sizeselect";
}
class DatabaseHelper {
static Database database;
//singleton instance
static DatabaseHelper sharedInstance = new DatabaseHelper._internal();
factory DatabaseHelper() {
return sharedInstance;
}
DatabaseHelper._internal();
Future<Database> get instance async {
if (database != null) {
return database;
}
database = await initDatabase();
return database;
}
initDatabase() async {
io.Directory documentDirectory = await getApplicationDocumentsDirectory();
String path = join(documentDirectory.path, databaseName);
var db = await openDatabase(path,
version: databaseVersion, onCreate: _onCreateTables);
return db;
}
_onCreateTables(Database db, int version) async {
await createCartTable(db);
}
Future createCartTable(Database db) async {
await db.execute(
"CREATE TABLE ${CartTable.tbCartDetails} ( ${CartTable.colID} INTEGER PRIMARY KEY AUTOINCREMENT, ${CartTable.colTitle} TEXT NOT NULL,"
" ${CartTable.colImage} TEXT NOT NULL, ${CartTable.colPrice} TEXT NOT NULL, ${CartTable.colColor} TEXT NOT NULL,"
" ${CartTable.colSizeSelect} TEXT NOT NULL )");
}
/// Insert Record
Future<dynamic> insertRecord(dynamic data, String tableName) async {
var dbClient = await instance;
return await dbClient.insert(tableName, data.toJson(),
conflictAlgorithm: ConflictAlgorithm.replace);
}
/// Get records
Future<List<dynamic>> getRecords(String table,
{List<String> columns,
String where,
List<dynamic> args,
String groupBy,
String orderBy,
int limit,
int offset}) async {
var dbClient = await instance;
return await dbClient.query(table,
columns: columns,
where: where,
whereArgs: args,
groupBy: groupBy,
orderBy: orderBy,
limit: limit,
offset: offset);
}
/// Update records
Future<dynamic> updateRecord(
{#required String table,
#required List<String> whereColumns,
#required List<dynamic> valuesCondition,
#required Map updateData}) async {
var dbClient = await instance;
String where = '';
whereColumns.forEach((column) => where += " $column=? and");
where = where.substring(0, where.length - 3);
debugPrint(
"Update => $table -> where :$where values:$valuesCondition Data:$updateData");
return await dbClient.update(table, updateData,
where: where, whereArgs: valuesCondition);
}
/// Delete records
Future<dynamic> deleteRecord(
{#required String table,
List<String> whereColumns,
List<dynamic> valuesCondition}) async {
var dbClient = await instance;
String where = '';
whereColumns.forEach((column) => where += " $column=? and");
where = where.substring(0, where.length - 3);
return await dbClient.delete(table,
where: where, whereArgs: valuesCondition);
}
Future close() async {
var dbClient = await instance;
dbClient.close();
}
}
Now, If you want to insert Data into cart_details table
var cart = Cart();
cart.id = widget.product.id;
cart.title = widget.product.title;
cart.image = widget.product.image;
cart.price = widget.product.normalPrice;
cart.color = selectedColor;
cart.sizeselect = selectedSize;
// This needs only once in main.dart
await DatabaseHelper.sharedInstance.initDatabase();
await DatabaseHelper.sharedInstance.insertRecord(cart,CartTable.tbCartDetails);

How to fix factory DbHelper class in flutter?

I have an error on the flutter run. Probably, some problem is on
//podesavanje singltona 2/3
DbHelper()._internal();
//podesavanje singltona 3/3
factory DbHelper() {
return _dbHelper;
}
in dbhelper.dart file. Any idea how to solve that?
dbhelper.dart
import 'package:sqflite/sqflite.dart';
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:todo_app/model/todo.dart';
class DbHelper {
//podesavanje singltona 1/3
static final DbHelper _dbHelper = DbHelper()._internal();
//table name
String tblName = "todo";
//columns
String colId = "id";
String colTitle = "title";
String colDescription = "description";
String colPriority = "priority";
String colDate = "date";
//podesavanje singltona 2/3
DbHelper()._internal();
//podesavanje singltona 3/3
factory DbHelper() {
return _dbHelper;
}
static Database _db;
Future<Database> get db async {
if (_db == null) {
_db = await initializeDb();
}
return _db;
}
//za ovo koristimo 'dart:io';
Future<Database> initializeDb() async {
Directory dir = await getApplicationDocumentsDirectory();
String path = dir.path + "todos.db";
var dbTodos = await openDatabase(path, version: 1, onCreate: _createDb);
return dbTodos;
}
void _createDb(Database db, int newVersion) async {
await db.execute(
"CREATE TABLE $tblName($colId INTEGER PRIMARY KEY, $colTitle TEXT, $colDescription TEXT, $colPriority INTEGER, $colDate TEXT)"
);
}
Future<int> insertTodo(Todo todo) async{
Database db = await this.db;
var result = await db.insert(tblName, todo.toMap());
return result;
}
Future<List> getTodos() async {
Database db = await this.db;
var result = await db.rawQuery("SELECT * FROM $tblName order by $colPriority ASC");
return result;
}
Future<int> getCount() async {
Database db = await this.db;
var result = Sqflite.firstIntValue(
await db.rawQuery("SELECT COUNT(*) FROM $tblName")
);
return result;
}
Future<int> updateTodo(Todo todo) async{
Database db = await this.db;
var result = await db.update(tblName, todo.toMap(), where: "$colId = ?", whereArgs: [todo.id]);
return result;
}
Future<int> deleteTodo(int id) async{
Database db = await this.db;
var result = await db.rawDelete("DELETE FROM $tblName WHERE $colId = $id");
return result;
}
}
todo.dart
import 'package:flutter/scheduler.dart';
class Todo {
//_ se stavlja zato da budu privatni
int _id;
String _title;
String _description;
String _date;
int _priority;
//postavljanje konstruktora, ne moze isti vise puta, opcioni ide u []
Todo(this._title, this._priority, this._date, [this._description]);
Todo.withId(this._id, this._title, this._priority, this._date,
[this._description]);
//geteri
int get id => _id;
String get title => _title;
String get description => _description;
String get date => _date;
int get priority => _priority;
//seteri
set title(String newTitle) {
if (newTitle.length < 255) {
_title = newTitle;
}
}
set description(String newDescription) {
if (newDescription.length < 255) {
_description = newDescription;
}
}
set priority(int newPriority) {
if (newPriority > 0 && newPriority <= 3) {
_priority = newPriority;
}
}
set date(String newDate) {
_date = newDate;
}
Map<String, dynamic> toMap() {
var map = Map<String, dynamic>();
map["title"] = _title;
map["description"] = _description;
map["priority"] = _priority;
map["date"] = _date;
if (_id != null) {
map["id"] = _id;
}
return map;
}
Todo.fromObject(dynamic o) {
this._id = o["id"];
this._title = o["title"];
this._description = o["description"];
this._date = o["date"];
this._priority = o["priority"];
}
}
main.dart
import 'package:flutter/material.dart';
import 'package:todo_app/util/dbhelper.dart';
import 'package:todo_app/model/todo.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
List<Todo> todos = List<Todo>();
DbHelper helper = DbHelper();
helper
.initializeDb()
.then((result) => helper.getTodos().then((result) => todos = result));
DateTime today = DateTime.now();
Todo todo = Todo("naslov", 1, today.toString(), "opcioni diskripsn");
helper.insertTodo(todo);
}
}
flutter run
Launching lib/main.dart on iPhone 8 Plus in debug mode...
Running Xcode build...
Xcode build done. 10.4s
Failed to build iOS app
Error output from Xcode build:
↳
** BUILD FAILED **
Xcode's output:
↳
lib/util/dbhelper.dart:19:13: Error: Expected '{' before this.
DbHelper()._internal();
^
lib/util/dbhelper.dart:19:13: Error: Expected a class member, but got '.'.
DbHelper()._internal();
^
lib/util/dbhelper.dart:21:11: Error: 'DbHelper' is already declared in this scope.
factory DbHelper() {
^^^^^^^^
lib/util/dbhelper.dart:19:3: Context: Previous declaration of 'DbHelper'.
DbHelper()._internal();
^^^^^^^^
lib/util/dbhelper.dart:7:7: Error: The non-abstract class 'DbHelper' is missing implementations for these members:
- DbHelper._internal
Try to either
- provide an implementation,
- inherit an implementation from a superclass or mixin,
- mark the class as abstract, or
- provide a 'noSuchMethod' implementation.
class DbHelper {
^^^^^^^^
lib/util/dbhelper.dart:19:14: Context: 'DbHelper._internal' is defined here.
DbHelper()._internal();
^^^^^^^^^
lib/main.dart:14:23: Error: Can't use 'DbHelper' because it is declared more than once.
DbHelper helper = DbHelper();
^
lib/util/dbhelper.dart:9:37: Error: Can't use 'DbHelper' because it is declared more than once.
static final DbHelper _dbHelper = DbHelper()._internal();
^
Command PhaseScriptExecution failed with a nonzero exit code
note: Using new build systemnote: Planning buildnote: Constructing build description
This is what you are trying to do
class DbHelper {
//podesavanje singltona 1/3
static final DbHelper _dbHelper = DbHelper._internal();
//table name
String tblName = "todo";
//columns
String colId = "id";
String colTitle = "title";
String colDescription = "description";
String colPriority = "priority";
String colDate = "date";
//podesavanje singltona 2/3
DbHelper._internal();
//podesavanje singltona 3/3
factory DbHelper() {
return _dbHelper;
}
static Database _db;
Future<Database> get db async {
if (_db == null) {
_db = await initializeDb();
}
return _db;
}
//za ovo koristimo 'dart:io';
Future<Database> initializeDb() async {
Directory dir = await getApplicationDocumentsDirectory();
String path = dir.path + "todos.db";
var dbTodos = await openDatabase(path, version: 1, onCreate: _createDb);
return dbTodos;
}
void _createDb(Database db, int newVersion) async {
await db.execute(
"CREATE TABLE $tblName($colId INTEGER PRIMARY KEY, $colTitle TEXT, $colDescription TEXT, $colPriority INTEGER, $colDate TEXT)");
}
Future<int> insertTodo(Todo todo) async {
Database db = await this.db;
var result = await db.insert(tblName, todo.toMap());
return result;
}
Future<List> getTodos() async {
Database db = await this.db;
var result =
await db.rawQuery("SELECT * FROM $tblName order by $colPriority ASC");
return result;
}
Future<int> getCount() async {
Database db = await this.db;
var result = Sqflite.firstIntValue(
await db.rawQuery("SELECT COUNT(*) FROM $tblName"));
return result;
}
Future<int> updateTodo(Todo todo) async {
Database db = await this.db;
var result = await db.update(tblName, todo.toMap(),
where: "$colId = ?", whereArgs: [todo.id]);
return result;
}
Future<int> deleteTodo(int id) async {
Database db = await this.db;
var result = await db.rawDelete("DELETE FROM $tblName WHERE $colId = $id");
return result;
}
}
Remove () from DbHelper()._internal()
DbHelper()._internal(); => DbHelper._internal();