Tuesday 23 February 2021

Flutter Database Connection Using Dart, Android Studio & SQFLITE | Copy-Paste Code



You can download project from : 
https://unpossiblepog.com/codes/DART+FLUTTER/Flutter-And-Dart-Convert-SQFLITE-Data-Into-Map-And-Display-That-Data-In-Table-UI


Note : Watch the video if you are confused to you want to see the practical approach of instructions which are given below.

########## START ##########

 1. In “pubspec.yaml” file, inside “dependencies”, after “flutter”, paste the following code (make sure that following code should be at the same level as “flutter”):


sqflite: any #stable version at the time of publishing this article

path_provider: any #stable version at the time of publishing this article

intl: ^0.15.7

--------------------------

2. Create “database_connector.dart” file at the level of "main.dart" (or at any place which contains dart files )

Then paste the following code in “database_connector.dart” file:


import 'package:sqflite/sqflite.dart';

import 'dart:async';

import 'dart:io';

import 'package:path_provider/path_provider.dart';


class DatabaseConnect{

static Database _database;


Future<Database> get database async {


if (_database == null) {

_database = await initializeDatabase();

}

return _database;

}


Future<Database> initializeDatabase() async {

Directory directory = await getApplicationDocumentsDirectory();

String path = directory.path + 'tutorialdb.db';


var notesDatabase = await openDatabase(path, version: 1, onCreate: createTable);

return notesDatabase;

}


void createTable(Database db, int newVersion) async {


await db.execute('CREATE TABLE employee(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, address TEXT)');

}


Future<int> insertStatic() async {

Database db = await this.database;

var result = await db.rawInsert("INSERT INTO employee(name,address) VALUES('steve rogers','brooklyn')");

return result;

}


Future<List<Map<String, dynamic>>> getList() async {

Database db = await this.database;

var result = await db.rawQuery('SELECT * FROM employee order by id ASC');

return result;

}


}


--------------------------

3. Then in "main.dart" file, paste the following at top of page below other imports:


import 'dart:async';

import 'package:<your_app_name+path_if_database_connector_is_inside_folder>/database_connector.dart';

import 'package:sqflite/sqflite.dart';

--------------------------


4. Then in “main.dart” file, just above the end bracket of class (which extends state), paste the following code:



void JustPrint()

{

print('wow');

}


void DBConInsert(){

DatabaseConnect con = DatabaseConnect();


final Future<Database> dbFuture = con.initializeDatabase();

dbFuture.then((database) {

Future<int> noteListFutureInsert = con.insertStatic();

noteListFutureInsert.then((noteList) {

print(noteList);

});

});


}

void DBConDisplay(){

DatabaseConnect con = DatabaseConnect();


List<Map<String, dynamic>> list=[];

final Future<Database> dbFuture = con.initializeDatabase();

dbFuture.then((database) {


Future<List<Map<String, dynamic>>> noteListFuture = con.getList();

noteListFuture.then((emp_data) {


for(var i=0;i<emp_data.length;i++)

{

Map m=emp_data[i];

m.forEach((k,v) => print('${k}: ${v}'));

}


});

});


}



--------------------------


5. If you have a button, then it is good, otherwise add the button. And onPressed of that button, add “JustPrint”

(JustPrint is a normal/temporary function which we pasted in main.dart file, it only prints ‘wow’ in console)


--------------------------


6. Then open the console in ANDROID STUDIO (4. Run), run the project and click on button.

If you see ‘wow’ in console, then it is good. Otherwise, check the process again to see if any step is missing.


--------------------------


7. If it is displaying ‘wow’, remove the ‘JustPrint’ after ‘onPressed’, and add ‘DBConInsert’ instead.

Save it. Refresh the project. Then click on button only once.

It will insert a new row in database table and display id in console.


--------------------------


8. If above step works, remove ‘DBConInsert’ and add ‘DBConDisplay’, then again click on button.

Save it. Refresh the project. Then click on button.

It will display data columnwise.


########## END ##########


IGNORE THE INFORMATION GIVEN BELOW WHICH IS MORE DETAILED VERSION OF ABOVE INSTRUCTIONS.

Subscribe my Channel:- http://www.youtube.com/user/SanketRooney?sub_confirmation=1


Facebook Page:- https://www.facebook.com/UnpossibleNS


Twitter Account:- https://twitter.com/UnpossiblePOG


Blog :- https://unpossiblepog.blogspot.in/


Hey guys, now we shall be connecting the flutter app with database and Insert data. Also we shall display a data but only in console as our main aim is to connect database on SQFLITE.

Now, I created a blog which contains steps & code. Link is given in the description. Then you just have to follow my steps as per the video.


First, we shall create a new flutter application. I am using Android studio.


Observe that in project explorer, there is a “lib” folder and inside it is a dart file.


Now, the first step is to copy code from 1st point and open “pubspec.yaml” and paste code inside dependencies but at the same level as flutter text.


Then a bulb symbol will appear. Click on “pub get”. It shall download dependencies.

Or you can click on the link which appeared at the top side of window.


Lets run an ANDROID SIMULATOR and RUN the project. It will take several minutes to run the project first time.


Once ran, click on the bottom button which increases the CLICK COUNT and displays on screen.


In second step, we have to create a dart file with any name. I would prefer database_connector.dart. Make sure that it should be created inside “LIB” folder.

If you so desire, you can create a package folder and add that file inside it just like I am doing in this video.


Copy-paste the whole code from point 2 and paste it in database_connector.dart file.


In third step, you have to import that file & other libraries.

So paste the code at the top of main.dart file.


Then you need to give specific location of database_connector file. That is, your project name which in my case is “”tutorial1, then /, then package name if you database connector file is inside it, then /, then database connector file name.


Copy the code from 4th point,

Go to the ending curly bracket of class which is extending STATE class.

Paste the code just above the ending curly bracket.


5th point is to call a simple function called JustPrint on press of a button.

SAVE all files, Refresh the app. Or enable the HOT RELOAD.

The navigator for RUN Console is available at the bottom of android studio. As you can see that this function is only printing the text in RUN CONSOLE.


6th point is just that.


Now in 7th point, we have to call DBConInsert on button’s press event. That function will create a database, an employee table and insert one row.


SAVE IT and DO REFRESH if you don’t have HOT RELOAD.


Once clicked on button, it will display a new ID’s value in console.


Sometimes you may get this error. Just simply close SIMULATOR and ANDROID STUDIO OR VISUAL STUDIO CODE and restart them. And do this step again.


Now,, if you get an ID on click of button, go to 8th and last step. And copy DBCONDISPLAY function and paste it at on press event of button.


Click on button and you will get all the data in console. Lets insert new row. And display them again to confirm.


Now you can play around with code and you can figure out how the code works.


So that is it, thanks for watching. Like share and subscribe.