Null value is saving instead of entered value in Flutter - flutter

I am receiving a null values when I am calling the getItems() method in database_client.dart file (retrieving all items name) ...so basically I am dealing with just two functions here which are saveItem() and getItems(). But itemName is storing in db as null value and i don't know why it is getting it as a null value ... there is no error in my code but the problem is that null values I am receiving of _itemName_and _dateCreated fields which are present in nodo_item.dart file.
I am going to give you my whole project code so that you can easily find out the problem here.
main.dart
import 'package:flutter/material.dart';
import 'package:no_to_do_app/ui/home.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
debugShowCheckedModeBanner: false,
title: 'NotoDo',
home: new Home(),
);
}
}
home.dart
import 'package:flutter/material.dart';
import 'package:no_to_do_app/ui/notodo_screen.dart';
class Home extends StatelessWidget {
const Home({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: Text('NoToDo'),
backgroundColor: Colors.black54,
),
body: new NoToDoScreen(
)
);
}
}
nodo_item.dart
import 'package:flutter/material.dart';
class NoDoItem extends StatelessWidget {
late String? _itemName;
late String? _dateCreated;
int? _id;
NoDoItem( this._itemName , this._dateCreated, {Key? key}) : super(key: key);
NoDoItem.map(dynamic obj, {Key? key}) : super(key: key)
{
_itemName = obj['ItemName'];
_dateCreated = obj['DateCreated'];
_id = obj['id'];
}
String? get itemName => _itemName;
String? get dateCreated => _dateCreated;
int? get id => _id;
Map<String , dynamic>toMap()
{
var map = <String , dynamic>{};
map['ItemName'] = _itemName;
map['DateCreated'] = _dateCreated;
/*if(_id !=null)
{
map['id'] = _id;
}*/
map['id'] = _id;
return map;
}
NoDoItem.fromMap(Map<String , dynamic>map, {Key? key}) : super(key: key)
{
_itemName = map['ItemName'];
_dateCreated = map['DateCreated'];
_id = map['id'];
}
#override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.all(8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(_itemName! ,
style: const TextStyle(
color: Colors.white,
fontSize: 16.5,
fontWeight: FontWeight.bold
),),
Container(
margin: const EdgeInsets.only(top: 5.0),
child: Text('Created on: $_dateCreated',
style: const TextStyle(
color: Colors.white70,
fontStyle: FontStyle.italic,
fontSize: 13.4
),),
)
],
)
);
}
}
database_client.dart
import 'dart:async';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:no_to_do_app/model/nodo_item.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
class DatabaseHelper
{
static final DatabaseHelper _instance = DatabaseHelper.private();
DatabaseHelper.private();
factory DatabaseHelper() => _instance;
final String tableName = "nodoTbl";
final String columnId = "id";
final String columnItemName = "itemName";
final String columnDateCreated = "dateCreated";
static late Database _db;
Future<Database> get database async
{
/*if(_db!=null)
{
return _db;
}*/
_db =await initDb();
return _db;
}
DatabaseHelper.internal();
initDb() async
{
Directory documentDirectory = await getApplicationDocumentsDirectory();
String path = join(documentDirectory.path, "notodo_db.db");
var ourDb= await openDatabase(path , version: 1 , onCreate: _onCreate);
return ourDb;
}
void _onCreate(Database db, int version) async
{
await db.execute(
"CREATE TABLE $tableName(id INTEGER PRIMARY KEY , $columnItemName TEXT ,$columnDateCreated TEXT)"
);
debugPrint('Table is Created');
}
Future<int> saveItem(NoDoItem item) async
{
var dbClient = await database;
int res =await dbClient.insert(tableName, item.toMap());
debugPrint(res.toString());
return res;
}
Future<List> getItems() async
{
var dbClient = await database;
var result = await dbClient.rawQuery("SELECT * FROM $tableName ORDER BY $columnItemName ASC");
return result.toList();
}
Future<int?> getCount() async
{
var dbClient = await database;
return Sqflite.firstIntValue(await dbClient.rawQuery(
"SELECT COUNT(*) FROM $tableName"
));
}
Future<NoDoItem?> getItem(int id) async{
var dbClient = await database;
var result = await dbClient.rawQuery("SELECT * FROM $tableName WHERE id=$id");
//if(result.length==0) return null;
if(result.isEmpty) return null;
return NoDoItem.fromMap(result.first);
}
Future<int> deleteItem(int id) async
{
var dbClient =await database;
return await dbClient.delete(tableName,where: "$columnId = ?", whereArgs: [id]);
}
Future<int> updateItem(NoDoItem item) async
{
var dbClient =await database;
return await dbClient.update(tableName, item.toMap(),
where: "$columnId=?", whereArgs: [item.id]);
}
Future close() async
{
var dbClient =await database;
return dbClient.close();
}
}
notodo_screen.dart
import 'package:flutter/material.dart';
import 'package:no_to_do_app/model/nodo_item.dart';
import 'package:no_to_do_app/util/database_client.dart';
class NoToDoScreen extends StatefulWidget {
const NoToDoScreen({Key? key}) : super(key: key);
#override
_NoToDoScreenState createState() => _NoToDoScreenState();
}
class _NoToDoScreenState extends State<NoToDoScreen> {
final TextEditingController _textEditingController = TextEditingController();
var db = DatabaseHelper();
#override
void initState() {
// TODO: implement initState
super.initState();
_readNotoDoItems();
}
void _hndleSubmitted(String text) async
{
_textEditingController.clear();
NoDoItem noDoItem = NoDoItem(text, DateTime.now().toIso8601String());
int savedItemId = await db.saveItem(noDoItem);
debugPrint("Item saved ID: $savedItemId");
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black87,
body: Column(),
floatingActionButton: FloatingActionButton(
tooltip: 'Add Item',
backgroundColor: Colors.redAccent,
child: const ListTile(
title: Icon(Icons.add)
),
onPressed: _showFormDialog),
);
}
void _showFormDialog() {
var alert = AlertDialog(
content: Row(
children: [
Expanded(
child: TextField(
controller: _textEditingController,
autofocus: true,
decoration: const InputDecoration(
labelText: 'item',
hintText: "eg. Don't buy Stuff",
icon: Icon(Icons.add_circle_outline_outlined)
),
))
],
),
actions: [
TextButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(Colors.blue),
),
onPressed: () {
_hndleSubmitted(_textEditingController.text);
_textEditingController.clear();
},
child: const Text("Save"),
),
TextButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(Colors.blue),
),
onPressed: () => Navigator.pop(context),
child: const Text("Cancel"),)
]
);
showDialog(context: context,
builder: (_) {
return alert;
});
}
_readNotoDoItems() async
{
List items = await db.getItems();
items.forEach((item) {
NoDoItem noDoItem = NoDoItem.map(item);
print("Db items: ${noDoItem.itemName}");
});
}
}
Output I am getting after running the project:
Performing hot restart...
Syncing files to device Android SDK built for x86...
Restarted application in 8,386ms.
I/flutter ( 3831): Db items: null
I/flutter ( 3831): Db items: null
I/flutter ( 3831): Db items: null
I/flutter ( 3831): Db items: null
I/flutter ( 3831): Db items: null
I/flutter ( 3831): Db items: null
I/flutter ( 3831): Db items: null
I/flutter ( 3831): Db items: null
I/flutter ( 3831): Db items: null
I/flutter ( 3831): Db items: null
I/flutter ( 3831): Db items: null
D/InputConnectionAdaptor( 3831): The input method toggled cursor monitoring on
I/TextInputPlugin( 3831): Composing region changed by the framework. Restarting the input method.
W/IInputConnectionWrapper( 3831): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper( 3831): getTextBeforeCursor on inactive InputConnection
D/InputConnectionAdaptor( 3831): The input method toggled cursor monitoring on
I/flutter ( 3831): 12
I/flutter ( 3831): Item saved ID: 12

Related

Flutter Bad state: cannot get a field on a DocumentSnapshotPlatform which does not exist

Im getting this error Bad state: cannot get a field on a DocumentSnapshotPlatform which does not exist , when i want to show current user name and email from firebase
Imported packages
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
Full code for profile page
class ProfilePage extends StatefulWidget {
const ProfilePage({Key? key}) : super(key: key);
#override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
String email = '';
String name = '';
Future getCurrentUserData() async{
try {
DocumentSnapshot ds = await FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser!.uid).get();
String email = ds.get('email');
String name = ds.get('name');
return [email,name];
}catch(e){
print(e.toString());
return null;
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child:
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(name),
Text(email),
MaterialButton(
onPressed: (){
FirebaseAuth.instance.signOut();
},
color: Colors.deepPurple,
child: const Text('Sign Out', style: TextStyle(color: Colors.white),),
),
MaterialButton(
onPressed: () async{
dynamic names = await getCurrentUserData();
if (names!=null) {
setState(() {
email = names[0];
name = names[1];
});
}
},
color: Colors.deepPurple,
child: const Text('DISPLAY DATA', style: TextStyle(color: Colors.white),),
),
],)),
);
}
}
Any ideas why ?
Don't use .get() on the DocumentSnapshot! Try this instead:
Future getCurrentUserData() async{
try {
final ref = FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser!.uid);
final ds = await ref.get();
final data = ds.data() as Map<String, dynamic>;
String email = data['email'];
String name = data['name'];
return [email,name];
}catch(e){
print(e.toString());
return null;
}
}
Change your function to:
Future getCurrentUserData() async{
try {
DocumentSnapshot ds = await FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser!.uid).get();
final data = ds.data();
String email = data!['email'];
String name = data!['name'];
return [email,name];
}catch(e){
print(e.toString());
return null;
}
}

Unhandled Exception: LateInitializationError: Field '_db#19320762' has not been initialized

import 'package:flutter/material.dart';
import 'package:sqlflite_demo/screens/product_list.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: ProductList(),
);
}
}
main.dart
class Product {
int? id;
String? name;
String? description;
double? unitPrice;
Product({this.name, this.description, this.unitPrice});
Product.withId({this.id, this.name, this.description, this.unitPrice});
Map<String,dynamic> toMap(){
var map = Map<String,dynamic>();
map["name"]=name;
map["description"]=description;
map["unitPrice"]=unitPrice;
if(id!=null){
map["id"]=id;
}
return map;
}
Product.fromObject(dynamic o){
this.id = int.tryParse(o["id"]);
this.name=o["name"];
this.description=o["description"];
this.unitPrice = double.tryParse(o["unitPrice"].toString());
}
}
product.dart
import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import '../models/product.dart';
class DbHelper {
late Database _db;
Future<Database> get db async {
if (_db == null) {
_db = await initializeDb();
}
return _db;
}
Future<Database> initializeDb() async {
String dbPath = join(await getDatabasesPath(), "etrade.db");
var eTradeDb = await openDatabase(dbPath,version: 1, onCreate: createDb);
return eTradeDb;
}
void createDb(Database db, int version)async {
await db.execute("Create table products(id integer primary key, name text, description text, unitPrice integer)");
}
Future<List<Product>> getProducts() async{
Database db = await this.db;
var result = await db.query("products");
return List.generate(result.length, (i){
return Product.fromObject(result[i]);
});
}
Future<int> insert(Product product)async{
Database db = await this.db;
var result = await db.insert("products", product.toMap());
return result; ////////
}
Future<int> delete(int id)async{
Database db = await this.db;
var result = await db.rawDelete("delete from products where id=$id");
return result;
}
Future<int> update(Product product)async{
Database db = await this.db;
var result = await db.update("products", product.toMap(), where: "id=?",whereArgs: [product.id]);
return result;
}
}
db_Helper.dart
import 'package:flutter/material.dart';
import 'package:sqlflite_demo/data/dbHelper.dart';
import 'package:sqlflite_demo/models/product.dart';
import 'package:sqlflite_demo/screens/product_add.dart';
class ProductList extends StatefulWidget{
#override
State<StatefulWidget> createState() {
return _ProductListState();
}
}
class _ProductListState extends State {
var dbHelper = DbHelper();
late List<Product> products;
int productCount =0;
#override
void initState() {
getProducts();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Ürün Listesi"),
),
body: buildProductList(),
floatingActionButton: FloatingActionButton(
onPressed: (){goToProductAdd();},
child: Icon(Icons.add),
tooltip: "Yeni Ürün Ekle",
),
);
}
ListView buildProductList() {
return ListView.builder(
itemCount: productCount,
itemBuilder: (BuildContext context, int position){
return Card(
color: Colors.pinkAccent,
elevation: 2.0,
child: ListTile(
leading: CircleAvatar(backgroundColor: Colors.black12, child: Text("P"),),
title: Text(products[position].name.toString()),
subtitle: Text(products[position].description.toString()),
onTap: (){},
),
);
});
}
void goToProductAdd() async{
bool result = await Navigator.push(context, MaterialPageRoute(builder: (context)=>ProductAdd()));
if(result!=null){
if(result){
getProducts();
}
}
}
void getProducts() async{
var productsFuture = dbHelper.getProducts();
productsFuture.then((data){
this.products = data;
productCount=data.length;
});
}
}
product_list.dart
import 'package:flutter/material.dart';
import 'package:sqlflite_demo/data/dbHelper.dart';
import '../models/product.dart';
class ProductAdd extends StatefulWidget{
#override
State<StatefulWidget> createState() {
return ProductAddState();
}
}
class ProductAddState extends State {
var dbHelper = DbHelper();
var txtName=TextEditingController();
var txtDescription=TextEditingController();
var txtUnitPrice=TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Yeni Ürün Ekle"),
),
body: Padding(
padding: EdgeInsets.all(30.0),
child: Column(
children: [
buildNameField(),buildDescriptionField(),buildUnitPriceField(),buildSaveButton()
],
),
),
);
}
buildNameField() {
return TextField(
decoration: InputDecoration(labelText: "Ürün Adı"),
controller: txtName,
);
}
buildDescriptionField() {
return TextField(
decoration: InputDecoration(labelText: "Ürün Açıklaması"),
controller: txtDescription,
);
}
buildUnitPriceField() {
return TextField(
decoration: InputDecoration(labelText: "Birim Fiyatı"),
controller: txtUnitPrice,
);
}
buildSaveButton() {
return FlatButton(
child: Text("Ekle"),
onPressed: (){
addProduct();
},
);
}
void addProduct() async{
var result = await dbHelper.insert(Product(name: txtName.text, description: txtDescription.text, unitPrice: double.tryParse(txtUnitPrice.text)));
Navigator.pop(context,true);
}
}
product_add.dart
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: LateInitializationError: Field '_db#19320762' has not been initialized.
This is my first project in flutter. and I have an error. can you explain that? Thanks. I dont know what happened

How do I resolve a Sqlite Error (1) in Flutter?

Im new to flutter and first time to work with sqlite database.
I have created a todo app that is linked to a Sqlite database. It has simple cards that i can add and it works fine. The problem is, I have a delete icon, but for some reason the cards do not delete when I press the delete icon. I get the following error message in the stack:
E/SQLiteLog(22653): (1) no such table: çustomerblueprint in "DELETE FROM çustomerblueprint WHERE id == ?"
E/flutter (22653): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: DatabaseException(no such table: çustomerblueprint (code 1 SQLITE_ERROR[1]): , while compiling: DELETE FROM çustomerblueprint WHERE id == ?) sql 'DELETE FROM çustomerblueprint WHERE id == ?' args [1]
I have read for hours to try and fine a solution, but don't seem to get this one.
My code is:
Database Code
class CustomerBluePrint {
int? id;
final String title;
DateTime creationDate;
bool isChecked;
CustomerBluePrint({
this.id,
required this.title,
required this.creationDate,
required this.isChecked,
});
Map<String, dynamic> toMap() {
return {
'id': id,
'title': title,
'creationDate': creationDate.toString(),
'isChecked': isChecked ? 1 : 0,
};
}
#override
String toString() {
return 'CustomerBluePrint(id : $id, title : $title, creationDate : $creationDate, isChecked
: $isChecked )'; // , phone : $phone, mobile : $mobile, fax : $fax, email : $email, name :
$name)';
}
}
class DatabaseConnect {
Database? _database;
Future<Database> get database async {
final dbpath = await getDatabasesPath();
const dbname = 'customerblueprint.db';
final path = join(dbpath, dbname);
_database = await openDatabase(path, version: 1, onCreate: _createDB);
return _database!;
}
Future<void> _createDB(Database db, int version) async {
await db.execute('''
CREATE TABLE todo(
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
creationDate TEXT,
isChecked INTEGER
)
''');
}
Future<void> insertCustomerBluePrint(
CustomerBluePrint customerblueprint) async {
final db = await database;
await db.insert(
'customerblueprint',
customerblueprint.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<void> deleteCustomerBluePrint(
CustomerBluePrint customerblueprint) async {
final db = await database;
await db.delete(
'çustomerblueprint',
where: 'id == ?',
whereArgs: [customerblueprint.id],
);
}
Future<List<CustomerBluePrint>> getCustomerBluePrint() async {
final db = await database;
List<Map<String, dynamic>> items = await db.query(
'customerblueprint',
orderBy: 'id DESC',
);
return List.generate(
items.length,
(i) => CustomerBluePrint(
id: items[i]['id'],
title: items[i]['title'],
creationDate: DateTime.parse(items[i]['creationDate']),
isChecked: items[i]['isChecked'] == 1 ? true : false,
),
);
}
}
Customer List Code
import 'package:flutter/material.dart';
import 'library.dart';
import 'customer_card.dart';
class CustomerList extends StatelessWidget {
final Function insertFunction;
final Function deleteFunction;
final db = DatabaseConnect();
CustomerList(
{required this.insertFunction, required this.deleteFunction, Key? key})
: super(key: key);
#override
Widget build(BuildContext context) {
return Expanded(
child: FutureBuilder(
future: db.getCustomerBluePrint(),
initialData: const [],
builder: (BuildContext context, AsyncSnapshot<List> snapshot) {
var data = snapshot.data;
var datalength = data!.length;
return datalength == 0
? const Center(
child: Text('no data found'),
)
: ListView.builder(
itemCount: datalength,
itemBuilder: (context, i) => CustomerCard(
id: data[i].id,
title: data[i].title,
creationDate: data[i].creationDate,
isChecked: data[i].isChecked,
insertFunction: insertFunction,
deleteFunction: deleteFunction,
),
);
},
),
);
}
}
Customer Card Code
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'library.dart';
class CustomerCard extends StatefulWidget {
final int id;
final String title;
final DateTime creationDate;
bool isChecked;
final Function insertFunction;
final Function deleteFunction;
CustomerCard(
{required this.id,
required this.title,
required this.creationDate,
required this.isChecked,
required this.insertFunction,
required this.deleteFunction,
Key? key})
: super(key: key);
#override
_CustomerCardState createState() => _CustomerCardState();
}
class _CustomerCardState extends State<CustomerCard> {
#override
Widget build(BuildContext context) {
var anotherCustomerBluePrint = CustomerBluePrint(
id: widget.id,
title: widget.title,
creationDate: widget.creationDate,
isChecked: widget.isChecked);
return Card(
child: Row(
children: [
Container(
margin: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
child: Checkbox(
value: widget.isChecked,
onChanged: (bool? value) {
setState(() {
widget.isChecked = value!;
});
anotherCustomerBluePrint.isChecked = value!;
widget.insertFunction(anotherCustomerBluePrint);
},
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.title,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
const SizedBox(height: 5),
Text(
DateFormat('dd MMM yyyy - hh:mm aaa')
.format(widget.creationDate),
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Color(0xFF8F8F8F),
),
)
],
),
),
IconButton(
onPressed: () {
widget.deleteFunction(anotherCustomerBluePrint);
},
icon: const Icon(Icons.close),
),
],
),
);
}
}
Customer Code
This is my Homepage
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:invoice_app/customer_profile.dart';
import 'customer_list.dart';
import 'library.dart';
class Customer extends StatefulWidget {
const Customer({Key? key}) : super(key: key);
#override
_CustomerState createState() => _CustomerState();
}
class _CustomerState extends State<Customer> {
var db = DatabaseConnect();
void addItem(CustomerBluePrint customerblueprint) async {
await db.insertCustomerBluePrint(customerblueprint);
setState(() {});
}
void deleteItem(CustomerBluePrint customerblueprint) async {
await db.deleteCustomerBluePrint(customerblueprint);
setState(() {
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFF5EBFF),
body: Column(
children: [
CustomerList(
insertFunction: addItem, deleteFunction: deleteItem),
CustomerProfile(
insertFunction: addItem
),
],
),
);
}
The deletefunction is suppose to delete an entry based on the 'id'assigned to it. Everything works fine, except I cannot delete a card (entry) as it throws the error.
Please help. Would really appreciate it.
Found your mistake take a look at Database Code and implementation of the method Future<void> deleteCustomerBluePrint(CustomerBluePrint customerblueprint) You have an error there. Your:
await db.delete(
'çustomerblueprint',
where: 'id == ?',
whereArgs: [customerblueprint.id],
);
Mine Repaired:
await db.delete(
'customerblueprint',
where: 'id == ?',
whereArgs: [customerblueprint.id],
);
An error in the word customerblueprint, you do not have the letter "c" there, you have some other sign.

I am able to save but not able to fetch the saved notes dynamically from DB, when I restart the app the notes are displaying. I am using sqflite

I'm a beginner in flutter, I'm building a simple Note app where users can enter, edit and save the note in local db. I'm able to save the notes to DB but it is not fetched as soon as it is saved. I need to restart the app to see the note list.
This is a Notes model class
import 'db_operations.dart';
class Note {
int id;
String title;
String body;
Note(this.id, this.title, this.body);
Note.fromMap(Map<String, dynamic> map) {
id = map['id'];
title = map['title'];
body = map['body'];
}
Map<String, dynamic> toMap(){
return {
DatabaseHelper.columnId : id,
DatabaseHelper.columnTitle : title,
DatabaseHelper.columnBody : body
};
}
#override
String toString(){
return 'Note{title : $title, body : $body}';
}
}
This is a Database helper class
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'model_notes.dart';
class DatabaseHelper {
static final _databaseName = "myNote.db";
static final _databaseVersion = 1;
static final table = 'notes_table';
static final columnId = 'id';
static final columnTitle = 'title';
static final columnBody = 'body';
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
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;
}
initDatabase() async {
String path = join(await getDatabasesPath(), _databaseName);
return await openDatabase(path,
version: _databaseVersion,
onCreate: _onCreate);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE $table (
$columnId INTEGER PRIMARY KEY AUTOINCREMENT,
$columnTitle TEXT NOT NULL,
$columnBody TEXT NOT NULL
)
''');
}
Future<int> insert(Note note) async {
Database db = await instance.database;
if (note.title.trim().isEmpty) note.title = 'Untitled Note';
return await db.insert(table, {'title': note.title, 'body': note.body});
}
Future<List<Note>> getNotesFromDB() async {
final db = await database;
List<Note> notesList = [];
List<Map> maps = await db.query(table);
if (maps.length > 0) {
maps.forEach((map) {
notesList.add(Note.fromMap(map));
});
}
return notesList;
}
}
This is where I am adding notes
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:note_taking_app/constants/buttons_and_icons_misc(classes).dart';
import 'package:note_taking_app/db/db_operations.dart';
import 'package:note_taking_app/db/model_notes.dart';
import 'package:sqflite/sqflite.dart';
import 'main_screen.dart';
final bodyController = TextEditingController();
final headerController = TextEditingController();
final dbHelper = DatabaseHelper.instance;
class AddingNotes extends StatefulWidget {
#override
_AddingNotesState createState() => _AddingNotesState();
}
class _AddingNotesState extends State<AddingNotes> {
#override
void initState() {
super.initState();
bodyController.clear();
headerController.clear();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backwardsCompatibility: true,
leading: LeadingIcon(
callBack: () {
Navigator.pop(context);
},
),
backgroundColor: Colors.white.withOpacity(0.4),
actions: <Widget>[
ActionsIconButton(
icon: Icon(undo, color: black),
callBack: () {
debugPrint('undo tapped');
},
),
ActionsIconButton(
icon: Icon(redo, color: black),
callBack: () {
debugPrint('redo tapped');
},
),
ActionsIconButton(
icon: Icon(save, color: black),
callBack: () async {
debugPrint(bodyController.text);
debugPrint(headerController.text);
String title = headerController.text;
String body = bodyController.text;
Note note = Note(20, title, body);
var value = await dbHelper.insert(note);
print("if 1 is return then insert success and 0 then not inserted : $value");
Navigator.pop(context);
},
)
],
),
body: Container(
color: Colors.white.withOpacity(0.4),
child: Padding(
padding: const EdgeInsets.all(13.0),
child: Column(
children: [
HeaderBody(
textEditingController: headerController,
),
SizedBox(
height: 32.0,
),
Expanded(
child: NotesBody(
textEditingController: bodyController,
),
),
],
),
),
),
);
}
}
This is where I am displaying notes
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:note_taking_app/constants/text_and_decorations(methods).dart';
import 'package:note_taking_app/db/model_notes.dart';
import 'package:note_taking_app/ui/adding_notes.dart';
import 'package:note_taking_app/db/db_operations.dart';
class MainScreen extends StatefulWidget {
#override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
List<Note> noteList = [];
#override
void initState() {
super.initState();
dbHelper.initDatabase();
setNotesFromDB();
}
setNotesFromDB() async{
print("Entered setNotes");
var fetchedNotes = await dbHelper.getNotesFromDB();
setState(() {
noteList = fetchedNotes;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
title: titleText,
backwardsCompatibility: false,
automaticallyImplyLeading: false,
backgroundColor: Colors.white.withOpacity(0.4),
),
floatingActionButton: Container(
height: 80.0,
width: 80.0,
child: FittedBox(
child: FloatingActionButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => AddingNotes()));
},
child: const Icon(
Icons.add,
),
backgroundColor: Colors.green,
),
),
),
body: ListView.builder(
itemCount: noteList.length,
itemBuilder: (context, index){
return ListTile(
title: Text('${noteList[index]}'),
);
},
),
);
}
}
When I restart the app I'm getting user-entered notes. How can I make this dynamic, as a user enters a note and save it, it should be displayed on Main Screen. but I don't know how to do that. Any help here guys, I'm stuck at this..
The problem is that you are using a future, once it is complete there will be no updates, unless the Widget calling the getNotesFromDB() gets rebuild, which is the case when you restart the app or the emulator.
Moreover, you are also only fetching the notes in initState() of your MainScreen.
Option 1:
Try turning your ListView.builder in the body into a streambuilder, which is refreshing your Screen whenever a new note is saved.
Option 2:
Alternatively, implement a pull-to-refresh logic, which calls getNotesFromDB() for you. Checkout this video from the FlutterTeam to implement the feature.

Unhandled Exception: NoSuchMethodError: The method 'insert' was called on null. Flutter

I modified the basic sqlLite example to fit a more dynamic list. But its probably not the best method of doing it. Anyway the Database code looks like this:
import 'package:sqflite/sqflite.dart';
import 'package:sqflite/sqlite_api.dart';
import 'Entry.dart';
import 'package:path/path.dart';
class Database_ {
Future<Database> database ;
void openDBFunction() async {
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'Journal Entries.db');
database = openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute(
"CREATE TABLE entries( _entry TEXT, _date TEXT)"
);
});
}
Future<void> insertEntry(Entry entry) async {
final Database db = await database;
await db.insert(
'entry',
entry.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<List<Entry>> entries() async {
final Database db = await database;
final List<Map<String, dynamic>> maps = await db.query('entries');
return List.generate(maps.length, (i) {
return Entry(
maps[i]["_entry"],
maps[i]["_date"],
);
});
}
}
the main.dart looks like this:
import 'package:flutter/material.dart';
import 'package:slide_journal/MainPage.dart';
import 'package:flutter/widgets.dart';
import 'package:slide_journal/Database_.dart';
main()async {
WidgetsFlutterBinding.ensureInitialized();
Database_().openDBFunction();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData.dark(),
home: MainPage(),
);
}
}
and then this is the input page:
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:slide_journal/Database_.dart';
import 'package:slide_journal/Entry.dart';
import 'List_of_Entries.dart';
// ignore: must_be_immutable
class MainPage extends StatelessWidget{
TextEditingController _controller = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.vertical(bottom: Radius.circular(30))),
title: Text("Home"),
toolbarHeight: 50,
automaticallyImplyLeading: false,
actions:<Widget> [IconButton(
icon: Icon(Icons.list_alt_sharp),
onPressed: () =>{
Navigator.push(context, (MaterialPageRoute(builder: (context)=>ListOfEntries())))
},
),
]
),
drawer: new Drawer(
child: new ListView(
children: <Widget>[
new DrawerHeader(
child: Text("Trisha is baby", style: new TextStyle(fontSize: 20),),
)
],
),
),
body: Center(
child: SingleChildScrollView(
child: Column(
children: [
Container(
height: 600,
width: 350,
child: TextField(
enabled: true,
controller: _controller,
enableSuggestions: true,
decoration: InputDecoration(
hintText: "Use text, emojis...",
suffixIcon: IconButton(
onPressed: () => {
addEntry(_controller.toString(), "DateTime.now().toString()"),
},
icon: Icon(Icons.send_outlined),
),
),
keyboardType: TextInputType.multiline,
style: TextStyle(fontSize: 30),
maxLength: 100,
),
)
],
),
)
),
);
}
void addEntry(String entry_, String date_)async {
final entry = Entry(
entry_,
date_
);
Database_().insertEntry(entry);
}
}
This is the error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: NoSuchMethodError: The method 'insert' was called on null.
Database is not intialized in your app. Do as below
class DatabaseHelper {
static String tableName = 'entries';
static late Database _database;
static Future<Database> get database async {
final databasePath = await getDatabasesPath();
final status = await databaseExists(databasePath);
if (!status) {
_database = await openDatabase(join(databasePath, 'notes_database.db'),
onCreate: (database, version) {
return database.execute(
"CREATE TABLE entries( _entry TEXT, _date TEXT)"
);
}, version: 1);
}
return _database;
}
static Future<bool> insertDb(Model yourModel) async {
final db = await database;
try {
await db.insert(your insert cmd);
} on Error {
throw Error();
}
return true;
}
}
database is not initialized. It has to be initialized before you can turn objects into it.