I have a screen that is reading data from a database table (sqllite) but the data is not been display in my listview. it looks like when i read the data the screen already display the gui and my array is not populated with data by the time the listview access the array.
below is my code
import 'package:finsec/model/cardview_list_item.dart';
import 'package:flutter/material.dart';
import 'package:finsec/utils/strings.dart';
import 'package:finsec/utils/colors.dart';
import 'package:finsec/widget/circle_icon.dart';
import 'package:finsec/data/db_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:finsec/utils/queries.dart';
class CardviewListItemData extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return CardviewListItemDataState();
}
}
class CardviewListItemDataState extends State<CardviewListItemData> {
DBProvider db = new DBProvider();
List<String> amountList;
List<CardviewListItem> listItems = List<CardviewListItem>();
int count = 0;
#override
Widget build(BuildContext context) {
if (amountList == null) {
amountList = List<String>();
updateListView();
listItems = summaryList();
}
return ListView.builder(
itemCount: listItems.length,
shrinkWrap: true,
itemBuilder: (context, index) {
return ListTile(
leading: Icon(listItems[index].icon, color: listItems[index].iconColor),
title: Align(
child: new Text(listItems[index].title,style: TextStyle(fontSize: 16)),
alignment: Alignment(-1.4, 0),
),
trailing: new Text(listItems[index].amount, style: TextStyle(fontSize: 16),),
//onTap: () => onTapped(context, listItems[index].title),
);
},
);
}
List<CardviewListItem> summaryList() {
List<CardviewListItem> summaryListItems = List<CardviewListItem>();
CardviewListItem income = new CardviewListItem(
title: totalIncome,
amount: amountList[0],
icon: Icons.attach_money,
iconColor: green
);
summaryListItems.add(income);
return summaryListItems;
}
void updateListView() {
final Future<Database> dbFuture = db.initializeDatabase();
dbFuture.then((database) {
Future<List<String>> incomeListFuture = db.getDataList(test);
incomeListFuture.then((amountList) {
setState(() {
this.amountList = amountList;
this.count = this.amountList.length;
});
});
});
}
}
my database code is
import 'dart:io';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:finsec/model/transaction_content.dart';
import 'package:finsec/utils/tables.dart';
import 'package:finsec/model/income/income_dao.dart';
import 'package:finsec/model/income/income.dart';
import 'package:finsec/model/list_item.dart';
import 'package:finsec/model/dao.dart';
import 'package:finsec/model/cardview_list_item.dart';
import 'package:finsec/utils/strings.dart';
import 'package:finsec/utils/colors.dart';
import 'package:finsec/widget/circle_icon.dart';
import 'package:finsec/data/db_provider.dart';
class DBProvider {
static DBProvider db; // Singleton DBProvider
static Database _database; // Singleton Database
DBProvider._createInstance(); // Named constructor to create instance of DBProvider
factory DBProvider() {
if (db == null) {
db = DBProvider._createInstance(); // This is executed only once, singleton object
}
return db;
}
Future<Database> get database async {
if (_database == null) {
_database = await initializeDatabase();
}
return _database;
}
Future<Database> initializeDatabase() async {
// Get the directory path for both Android and iOS to store database.
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path + 'finsec.db';
// Open/create the database at a given path
var finsecDatabase = await openDatabase(path, version: 4, onCreate: _createDb, onUpgrade: _onUpgrade);
return finsecDatabase;
}
void _createDb(Database db, int newVersion) async {
// await db.execute('drop table income');
print('CREATE THE TABLE2');
await db.execute(incomeTable);
//await db.execute("CREATE TABLE User(id INTEGER PRIMARY KEY, firstname TEXT, lastname TEXT, dob TEXT)");
}
// UPGRADE DATABASE TABLES
void _onUpgrade(Database db, int oldVersion, int newVersion) async {
if (oldVersion < newVersion) {
await db.execute('drop table income');
await db.execute(incomeTable);
}
}
// Fetch Operation: Get all row objects from database
Future<List<Map<String, dynamic>>> getTransactions(String tableName) async {
Database db = await this.database;
//var result = await db.rawQuery(tableName);
var result = await db.query(tableName);
result.forEach((row) => print(row));
// var res = await db.insert('note', transactionType.toMap());
return result;
}
// Fetch Operation: Get all row objects from database
Future<List<Map<String, dynamic>>> getTransactionsQuery(String query) async {
Database db = await this.database;
var result = await db.rawQuery(query);
return result;
}
// Insert Operation: Insert a transaction object to database
Future<int> insertTransaction(String sqlQuery) async {
Database db = await this.database;
//var dao = new IncomeDao();
var result = await db.rawInsert(sqlQuery); //insert(noteTable, note.toMap());
//var result = await db.insert('noteTable', transaction);
return result;
}
// Update Operation: Update a Note object and save it to database
Future<int> updateTransaction(Map transaction) async {
var db = await this.database;
//var result = await db.rawUpdate(sql);// update(noteTable, note.toMap(), where: '$colId = ?', whereArgs: [note.id]);
var result = await db.update('noteTable', transaction);
return result;
}
// Delete Operation: Delete a transaction object from database
Future<int> deleteTransaction(int id) async {
var db = await this.database;
int result = await db.rawDelete('DELETE FROM noteTable WHERE ');
return result;
}
// Get number of Note objects in database
Future<int> getCount() async {
Database db = await this.database;
List<Map<String, dynamic>> x = await db.rawQuery('SELECT COUNT (*) from noteTable');
int result = Sqflite.firstIntValue(x);
return result;
}
// Get the 'Map List' [ List<Map> ] and convert it to 'Note List' [ List<Note> ]
Future<List<Income>> getIncomeList(String tableName) async {
var incomeMapList = await getTransactions(tableName); // Get 'Map List' from database
int count = incomeMapList.length; // Count the number of map entries in db table
List<Income> incomeList = List<Income>();
// For loop to create a 'Income List' from a 'Map List'
for (int i = 0; i < count; i++) {
incomeList.add(Income.fromMap(incomeMapList[i]));
}
return incomeList;
}
// Get the 'Map List' [ List<Map> ] and convert it to 'Note List' [ List<Note> ]
Future<List<String>> getDataList(String query) async {
var dataMapList = await getTransactionsQuery(query); // Get 'Map List' from database
int count = dataMapList.length; // Count the number of map entries in db table
List<String> dataList = List<String>();
Map<String, dynamic> queryData;
for (int i = 0; i < count; i++) {
queryData = dataMapList[i];
dataList.add(queryData["amount"]);
}
return dataList;
}
}
i think the problem is in the following portion of the code
if (amountList == null) {
amountList = List<String>();
updateListView();
listItems = summaryList();
}
updateListView() is getting called but it looks like the code continue executing to the next line even if updateListView didnt finish executing. when i called amountList[0] in summaryList(), i get the following error
RangeError (index): Invalid value: Valid value range is empty: 0
I/flutter ( 3640):
I/flutter ( 3640): User-created ancestor of the error-causing widget was:
I/flutter ( 3640): Column file:///C:/Users/rodrigue33/Documents/APP/finsec/lib/widget/cardview_widget.dart:45:22
I/flutter ( 3640):
I/flutter ( 3640): When the exception was thrown, this was the stack:
I/flutter ( 3640): #0 List.[] (dart:core-patch/growable_array.dart:145:60)
I/flutter ( 3640): #1 CardviewListItemDataState.summaryList (package:finsec/data/cardview_list_item.dart:114:27)
I/flutter ( 3640): #2 CardviewListItemDataState.build (package:finsec/data/cardview_list_item.dart:80:19)
I/flutter ( 3640): #3 StatefulElement.build (package:flutter/src/widgets/framework.dart:4040:27)
this is my assumption of what is happening. do anyone agree with me? how can i solve this issue of waiting for database to return data before displaying the data in the listview? thanks in advance
The problem is that you are calling the setState method and updating its "amountList", as setState reloads the page it doesn't quite execute "listItems = summaryList ();".
Perhaps a quick fix would be to create a bool check and leave it false, set to true when setState is executed, and within your builder method do:
if (amountList == null) {
amountList = List<String>();
updateListView();
}
if(check){
listItems = summaryList();
}
NOTE: I suggest using async and await in your methods instead of future.
void updateListView() async{
final Database db = await db.initializeDatabase();
List<String> incomeList = await db.getDataList(test);
setState(() {
this.amountList = amountList;
this.count = this.amountList.length;
this.check = true;
});
}
I hope I helped you!
Related
I new in Flutter.
I have already exist db and need add it to app.
Put file in assets/db/sms.db
in file pubspec.yaml
assets:
- assets/db/sms.db
Copy db file in applicationDirectory.
In file categoriesList.dart I try connect to it.
SmsDataBaseHelper.instance.getAllCategories()
I get error message.
database_helper.dart
import 'package:flutter/services.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'dart:io' as io;
import '/models/categories.dart';
class SmsDataBaseHelper {
static final SmsDataBaseHelper instance = SmsDataBaseHelper._();
static Database? _db;
SmsDataBaseHelper._();
Future<Database> get db async {
_db ??= await _init();
return _db!;
}
Future<Database> _init() async {
io.Directory applicationDirectory = await getApplicationDocumentsDirectory();
String dbPathSms = path.join(applicationDirectory.path, "sms.db");
bool dbExistsSms = await io.File(dbPathSms).exists();
if (!dbExistsSms) {
// Copy from asset
ByteData data = await rootBundle.load(path.join("assets", "db", "sms.db"));
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
// Write and flush the bytes written
await io.File(dbPathSms).writeAsBytes(bytes, flush: true);
}
return await openDatabase(dbPathSms);
}
/// get all the words from categories
Future<List<Categories>> getAllCategories() async {
if (_db == null) {
throw "_db is not initiated, initiate using [init(db)] function";
}
List<Map>? categories;
await _db!.transaction((txn) async {
categories = await txn.query(
"categories",
columns: [
"name",
"ru",
],
);
});
return categories!.map((e) => Categories.fromJson(e as Map<String, dynamic>)).toList();
}
}
categoriesList.dart
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import '../utils/database_helper.dart';
import '../models/categories.dart';
class CategoriesList extends StatefulWidget {
const CategoriesList({super.key});
#override
State<CategoriesList> createState() => _CategoriesListState();
}
class _CategoriesListState extends State<CategoriesList> {
//late List<Categories> categoriesList;
#override
void initState(){
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('SMS Home Page'),
),
body: FutureBuilder<List<Categories>>(
future: SmsDataBaseHelper.instance.getAllCategories(),
builder: (BuildContext context, AsyncSnapshot<List<Categories>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return const Text('start widget');
case ConnectionState.active:
case ConnectionState.waiting:
return const Text('Awaiting result from api...');
case ConnectionState.done:
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');
return Text('Result: ${snapshot.data}');
}
},
),
);
}
}
use this class to build database ..
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
class SqlDb {
static Database? _db;
Future<Database?> get db async {
if (_db == null) {
_db = await initialDb();
return _db;
} else {
return _db;
}
}
initialDb() async {
String databasepath = await getDatabasesPath();
String path = join(databasepath, 'shop.db');
Database mydb = await openDatabase(path,
onCreate: _onCreate, version: 1, onUpgrade: _onUpgrade);
return mydb;
}
_onUpgrade(Database db, int oldversion, int newversion) async {}
deletemydatabase() async {
String databasepath = await getDatabasesPath();
String path = join(databasepath, 'shop.db');
var x = await deleteDatabase(path);
return x;
}
_onCreate(Database db, int version) async {
await db.execute(
"CREATE TABLE cart (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT , title TEXT, size TEXT , code TEXT , img TEXT , price TEXT )");
}
//Select
readData(String sql) async {
Database? mydb = await db;
List<Map> response = await mydb!.rawQuery(sql);
return response;
}
//insert data
insertData(String sql) async {
Database? mydb = await db;
int response = await mydb!.rawInsert(sql);
return response;
}
deleteData(String sql) async {
Database? mydb = await db;
int response = await mydb!.rawDelete(sql);
return response;
}
updateData(String sql) async {
Database? mydb = await db;
int response = await mydb!.rawUpdate(sql);
return response;
}
}
I am trying to get an async function _read() to run and the function does not pass the line:
Reading reading = await helper.queryReading(rowId); in this function:
_read() async {
DatabaseHelper helper = DatabaseHelper.instance;
int rowId = 1;
//lines above here executes
Reading reading = await helper.queryReading(rowId); //this is the line it stops on
// nothing below here is executed
if (reading == null) {
print('read row $rowId: empty');
} else {
print('read row $rowId: ${reading.reading}');
}
}
It is being called from the following function
class Profile {
Widget getScreen(){
print("Attempting to read db");
_read();
return Scaffold( ...)
Here is my helper class:
import 'dart:ffi';
import 'dart:io';
import 'package:ema/Readings.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
//table structure
final String tableName = 'Readings';
final String databasecolumnId = '_id';
final String databaseReading = 'Reading';
final String databaseDate = 'Time';
class DatabaseHelper {
//This is the name of the database file on disk
static final _databaseName = "readings.db";
//handles versioning for databases
static final _databaseVersion = 1;
//makes a singleton classs
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
//allows only one item to access the database
static Database _database;
Future<Database> get database async {
_database = await _initDatabase();
return database;
}
//this opens and creates the database
_initDatabase() async {
// The path_provider plugin gets the right directory for Android or iOS.
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, _databaseName);
// Open the database. Can also add an onUpdate callback parameter.
return await openDatabase(path,
version: _databaseVersion,
onCreate: _onCreate);
}
//Creates the database
Future _onCreate(Database db, int version) async {
await db.execute(
'''
CREATE TABLE $tableName (
$databasecolumnId INTEGER PRIMARY KEY,
$databaseReading REAL NOT NULL,
$databaseDate INTERGER NOT NULL
)
'''
);
}
Future<int> insertReading(Reading reading) async {
Database db = await database;
int id = await db.insert(tableName, reading.toMap());
return id;
}
//gets reading
Future<Reading> queryReading(int id) async {
print("queryReading"); //gets here
Database db = await database;
print("Getting Db"); // not actually getting here
List<Map> maps = await db.query(tableName,
columns: [databasecolumnId, databaseReading, databaseDate],
where: '$databasecolumnId = ?',
whereArgs: [id]);
if (maps.length > 0) {
return Reading.fromMap(maps.first);
}
print('maps length : ${maps.length}');
return null;
}
}
Here is my Readings class:
class Reading {
int id;
double reading;
DateTime date;
//constructor
Reading({this.id, this.reading, this.date});
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
databaseReading: reading,
databaseDate: date.millisecondsSinceEpoch,
};
if (id != null) {
map[databasecolumnId] = id;
}
return map;
}
//extracts a node object from the map obect
Reading.fromMap(Map<String, dynamic> map) {
id = map[databasecolumnId];
reading = map[databaseReading];
date = new DateTime.fromMillisecondsSinceEpoch(map [databaseDate]);
}
}
Turns out there was a deadlock in getting the database. By putting a lock on it it worked.
Here is the code to resolve it:
///declreation of the database
Database _database;
///Gets the database ensuring that there are no locks currently on the database
Future<Database> get database async {
if (_database != null) return _database;
_database = await _initDatabase();
return _database;
}
I want to get the real Id of object how's I create in real time without close page and return back to it
because I use initState() to get data from Database and if I tried to get Id without do that it will return 1 ;
any one know why this happened and who to fix it ?
this my Function:
item(String name,String desc,int rate) async{
int savedItem = await db.saveMovie(Movie(name, desc,rate.toString()));
Movie addedItem = await db.getMovie(savedItem);
setState(() {
movies.add(addedItem);
});
print("Item id :${addedItem.id} Saved item : ${savedItem}");
}
and this my database helper code :
import 'dart:async';
import 'package:sqflite/sqflite.dart';
import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:mblists/models/movies.dart';
class DatabaseHelper {
final String moviesTable = "moviesTable";
final String idColumn = "id";
final String nameColumn = "name";
final String descriptionColumn = "description";
final String rateColumn = "rate";
static final DatabaseHelper _instance = DatabaseHelper.internal();
factory DatabaseHelper() => _instance;
static Database _db;
Future<Database> get db async{
if(_db != null){
return _db;
}
_db = await initDb();
return _db;
}
DatabaseHelper.internal();
initDb() async{
Directory fileDirectory = await getApplicationDocumentsDirectory();
String path = join(fileDirectory.path,"maindatabase.db");
var maindb = await openDatabase(path,version: 1,onCreate: _onCreate);
return maindb;
}
void _onCreate(Database db,int newVersion) async{
await db.execute(
"CREATE TABLE $moviesTable($idColumn INTEGER PRIMARY KEY, $nameColumn TEXT, $descriptionColumn TEXT, $rateColumn TEXT)");
}
Future<int> saveMovie(Movie movie) async{
var dbClient = await db;
int res = await dbClient.insert("$moviesTable", movie.toMap());
return res;
}
Future<List> getAllMovies() async{
var dbClient = await db;
var result = await dbClient.rawQuery("SELECT * FROM $moviesTable");
return result;
}
Future<Movie> getMovie(int id) async{
var dbClient = await db;
var result = await dbClient.rawQuery("SELECT * FROM $moviesTable WHERE $id = $id");
if(result.length == 0) {
return null;
}
return Movie.formMap(result.first);
}
Future<int> getCount() async {
var dbCllient = await db;
return Sqflite.firstIntValue(
await dbCllient.rawQuery("SELECT COUNT(*) FROM $moviesTable")
);
}
Future<int> deleteMovie(int id) async {
var dbClient = await db;
return await dbClient.delete(moviesTable,where: "$idColumn = ?",whereArgs: [ id]);
}
Future<int> deleteMovies() async {
var dbClient = await db;
return await dbClient.delete(moviesTable);
}
Future<int> updateMovie(Movie movie) async {
var dbClient = await db;
return await dbClient.update(moviesTable,movie.toMap(),
where: "$idColumn = ?" , whereArgs: [movie.id]
);
}
Future colse() async{
var dbClient = await db;
return await dbClient.close();
}
}
Insert method returns correct new id, but you have a typo in getMovie:
var result = await dbClient.rawQuery("SELECT * FROM $moviesTable WHERE $id = $id");
WHERE condition should contain column name, but your has id = id condition (which is always true) and then it takes the first element (always the same one). Fix it by passing id column's name:
var result = await dbClient.rawQuery("SELECT * FROM $moviesTable WHERE $idColumn = $id");
And it works:
I/flutter ( 5996): Item id :13 Saved item : {id: 13, name: test, description: desc, rate: 1}
I/flutter ( 5996): Item id :14 Saved item : {id: 14, name: test, description: desc, rate: 1}
I/flutter ( 5996): Item id :15 Saved item : {id: 15, name: test, description: desc, rate: 1}
I am working on SqFlite programme but it shows ArgumentError Exception.
My code is not working it showing I can not insert data into database.
Please some one help me with this.SQFlite Operation like CRUD is not performing.
Exception like ArgumentError Exception like occurring some default dart file with Exception Showing.
Exception throw ArgumentError("nullColumnHack required when inserting no data");
import 'dart:async';
import 'dart:io';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqlite_app/models/note.dart';
class DatabaseHelper {
static DatabaseHelper _databaseHelper;
static Database _database;
String noteTable = 'note_table';
String colId = 'id';
String colTitle = 'title';
String colDescription = 'description';
String colPriority = 'priority';
String colDate = 'date';
DatabaseHelper._createInstance();
factory DatabaseHelper(){
if (_databaseHelper == null) {
_databaseHelper = DatabaseHelper._createInstance();
}
return _databaseHelper;
}
Future<Database> get databse async {
if (_database == null) {
_database = await initalizeDatabase();
}
return _database;
}
Future<Database> initalizeDatabase() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path + 'note.db';
var noteDatabase = await openDatabase(
path, version: 1, onCreate: _createDb);
return noteDatabase;
}
void _createDb(Database db, int newVersion) async {
await db.execute(
'CREATE TABLE $noteTable ($colId INTEGER PRIMARY KEY AUTOINCREMENT,$colTitle TEXT,'
'$colDescription TEXT,$colPriority INTEGER,$colDate TEXT)');
}
Future<List<Map<String, dynamic>>> getNoteMapList() async {
Database db = await this.databse;
//var result=await db.rawQuery('SELECT * FROM $noteTable order by $colPriority ASC');
var result = await db.query(noteTable, orderBy: '$colPriority ASC');
return result;
}
Future<int> insertNote(Note note) async {
Database db = await this.databse;
var result = await db.insert(noteTable, note.toMap());
return result;
}
Future<int> updateNote(Note note) async {
var db = await this.databse;
var result = await db.update(
noteTable, note.toMap(), where: '$colId=?', whereArgs: [note.id]);
return result;
}
Future<int> deleteNote(int id) async {
var db = await this.databse;
int result = await db.rawDelete('DELETE FROM $noteTable WHERE $colId=$id');
return result;
}
Future<int> getCount() async {
Database db = await this.databse;
List<Map<String, dynamic>> x = await db.rawQuery(
"SELECT COUNT (*) from $noteTable");
int result = Sqflite.firstIntValue(x);
return result;
}
Future<List<Note>> getNoteList() async {
var noteMapList = await getNoteMapList();
int count = noteMapList.length;
List<Note> noteList = List<Note>();
for (int i = 0; i < count; i++) {
noteList.add(Note.fromMapObject(noteMapList[i]));
}
return noteList;
}
}
Just pass one more argument in db.insert(i.e. nullColumnHack) with value equal to the Auto Incrementing ID Integer...it will work...Do this for all other operations...
Future<int> insertNote(Note note) async {
Database db = await this.databse;
var result = await db.insert(noteTable, note.toMap(),nullColumnHack: colId);
return result;
}
So basically what i want to do is:
When the user turns on the app for the first time,
The SQLite database is created and the data is fetched from the internet.
Until this is done, SetupPage() widget is displayed in scaffolds body or else Home() is displayed.
Now the code i wrote works perfectly for the first time, but when i open it the second time,
The SetupPage() only shows, it never goes back to the Home(). What am i doing wrong here ?
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart';
import 'package:path/path.dart';
import 'pages/home.dart';
import 'pages/SetUpPage.dart';
import 'package:sqflite/sqflite.dart';
class App extends StatefulWidget {
createState() {
return AppState();
}
}
class AppState extends State<App> {
final bgColor = const Color(0xFF1abc9c);
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
bool status = false;
Database database;
#override
void initState() {
initializeData();
super.initState();
}
void initializeData() async
{
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'demo.db');
status = false;
Database database = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute(
'CREATE TABLE news (id INTEGER PRIMARY KEY, topic TEXT, img TEXT, newstitle TEXT, news TEXT, newslink TEXT)');
fetchData();
}
);
database.close();
}
#override
Widget build(context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text("UnFound News"),
backgroundColor: bgColor,
),
body: status ? Home() : SetUpPage(),
);
}
/*Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);*/
void fetchData() async {
var result = await get("https://api.myjson.com/bins/a0bvu");
var arr = json.decode(result.body)['post'];
for(int i = 0; i < arr.length; i++)
{
//TODO: Implement addition to database.
}
setState(() {
status = true;
});
}
}
You probably want to put the fetchData in a onOpen parameter instead of the onCreate parameter like this:
Database database = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute(
'CREATE TABLE news (id INTEGER PRIMARY KEY, topic TEXT, img TEXT, newstitle TEXT, news TEXT, newslink TEXT)');
await fetchData();
}, onOpen: (Database db) async {
setState(() {
status = true;
});
});
static Database _db;
Future<Database> get db async {
if(_db != null)
return _db;
_db = await initDb();
return _db;
}
//Creating a database with name test.dn in your directory
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "test.db");
var theDb = await openDatabase(path, version: 1, onCreate: _onCreate);
return theDb;
}
checkDb(){
//do operation
var dbClient = await db;
}