First, we must create a project using Visual Studio Code software. Here's how to create a new project using Visual Studio Code:
After the new project is created, create the database file in the directory application that was created (e.g [projectname]/data/[databasename].db).
We must prepare the database using sqlite first. All we have to do is create a file with the .db extension first.
Edit file pubspec.yaml in your directory and it should look something like this:
- name: login
- description: A new Flutter project.
-
- # The following defines the version and build number for your application.
- # A version number is three numbers separated by dots, like 1.2.43
- # followed by an optional build number separated by a +.
- # Both the version and the builder number may be overridden in flutter
- # build by specifying --build-name and --build-number, respectively.
- # In Android, build-name is used as versionName while build-number used as versionCode.
- # Read more about Android versioning at https:
- # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
- # Read more about iOS versioning at
- # https:
- version: 1.0.0+1
-
- environment:
- sdk: ">=2.1.0 <3.0.0"
-
- dependencies:
- flutter:
- sdk: flutter
-
- # The following adds the Cupertino Icons font to your application.
- # Use with the CupertinoIcons class for iOS style icons.
- cupertino_icons: ^0.1.2
- sqflite: any
- path_provider: ^0.4.0
- shared_preferences: ^0.5.4
-
- dev_dependencies:
- flutter_test:
- sdk: flutter
-
- # For information on the generic Dart part of this file, see the
- # following page: https:
-
- # The following section is specific to Flutter.
- flutter:
-
- # The following line ensures that the Material Icons font is
- # included with your application, so that you can use the icons in
- # the material Icons class.
- uses-material-design: true
-
- assets:
- - data/flutter.db
- # To add assets to your application, add an assets section, like this:
- # assets:
- # - images/a_dot_burr.jpeg
- # - images/a_dot_ham.jpeg
-
- # An image asset can refer to one or more resolution-specific "variants", see
- # https:
-
- # For details regarding adding assets from package dependencies, see
- # https:
-
- # To add custom fonts to your application, add a fonts section here,
- # in this "flutter" section. Each entry in this list should have a
- # "family" key with the font family name, and a "fonts" key with a
- # list giving the asset and other descriptors for the font. For
- # example:
- # fonts:
- # - family: Schyler
- # fonts:
- # - asset: fonts/Schyler-Regular.ttf
- # - asset: fonts/Schyler-Italic.ttf
- # style: italic
- # - family: Trajan Pro
- # fonts:
- # - asset: fonts/TrajanPro.ttf
- # - asset: fonts/TrajanPro_Bold.ttf
- # weight: 700
- #
- # For details regarding fonts from package dependencies,
- # see https:
We’re going to need to create a user.dart in directory [projectname]/lib/models which helps us manage a user's data.
- class User {
- int _id;
- String _username;
- String _password;
-
- User(this._username, this._password);
-
- User.fromMap(dynamic obj) {
- this._username = obj['username'];
- this._password = obj['password'];
- }
-
- String get username => _username;
- String get password => _password;
-
- Map<String, dynamic> toMap() {
- var map = new Map<String, dynamic>();
- map["username"] = _username;
- map["password"] = _password;
- return map;
- }
- }
And to database_helper.dart:
- import 'dart:io';
- import 'dart:typed_data';
- import 'package:flutter/services.dart';
- import 'package:login/models/user.dart';
- import 'package:path/path.dart';
- import 'dart:async';
- import 'package:path_provider/path_provider.dart';
- import 'package:sqflite/sqflite.dart';
-
- class DatabaseHelper {
- static final DatabaseHelper _instance = new 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 documentDirectory = await getApplicationDocumentsDirectory();
- String path = join(documentDirectory.path, "data_flutter.db");
-
-
-
-
- ByteData data = await rootBundle.load(join('data', 'flutter.db'));
- List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
-
-
- await new File(path).writeAsBytes(bytes);
-
-
- var ourDb = await openDatabase(path);
- return ourDb;
- }
- }
After we create database_helper.dart, next create file for the query to get data for user login. The file login_ctr.dart looks ike below,
- import 'package:login/models/user.dart';
- import 'dart:async';
- import 'package:login/data/database_helper.dart';
-
- class LoginCtr {
- DatabaseHelper con = new DatabaseHelper();
-
-
- Future<int> saveUser(User user) async {
- var dbClient = await con.db;
- int res = await dbClient.insert("User", user.toMap());
- return res;
- }
-
-
- Future<int> deleteUser(User user) async {
- var dbClient = await con.db;
- int res = await dbClient.delete("User");
- return res;
- }
-
- Future<User> getLogin(String user, String password) async {
- var dbClient = await con.db;
- var res = await dbClient.rawQuery("SELECT * FROM user WHERE username = '$user' and password = '$password'");
-
- if (res.length > 0) {
- return new User.fromMap(res.first);
- }
-
- return null;
- }
-
- Future<List<User>> getAllUser() async {
- var dbClient = await con.db;
- var res = await dbClient.query("user");
-
- List<User> list =
- res.isNotEmpty ? res.map((c) => User.fromMap(c)).toList() : null;
-
- return list;
- }
- }
Here there is also a service that functions to request and respond to a request made by an existing feature. For example, to request a login function such as the following request and response, we must create file
login_response.dart &
login_request.dart like below,
- import 'package:login/services/request/login_request.dart';
- import 'package:login/models/user.dart';
-
- abstract class LoginCallBack {
- void onLoginSuccess(User user);
- void onLoginError(String error);
- }
-
- class LoginResponse {
- LoginCallBack _callBack;
- LoginRequest loginRequest = new LoginRequest();
- LoginResponse(this._callBack);
-
- doLogin(String username, String password) {
- loginRequest
- .getLogin(username, password)
- .then((user) => _callBack.onLoginSuccess(user))
- .catchError((onError) => _callBack.onLoginError(onError.toString()));
- }
- }
login_request.dart
- import 'dart:async';
-
- import 'package:login/models/user.dart';
- import 'package:login/data/CtrQuery/login_ctr.dart';
-
- class LoginRequest {
- LoginCtr con = new LoginCtr();
-
- Future<User> getLogin(String username, String password) {
- var result = con.getLogin(username,password);
- return result;
- }
- }
Later, we create login_screen.dart
- import 'package:flutter/material.dart';
- import 'package:login/models/user.dart';
- import 'package:login/screen/home_page.dart';
- import 'package:login/services/response/login_response.dart';
- import 'package:shared_preferences/shared_preferences.dart';
-
- class LoginPage extends StatefulWidget {
- @override
- _LoginPageState createState() => new _LoginPageState();
- }
-
- enum LoginStatus { notSignIn, signIn }
-
- class _LoginPageState extends State<LoginPage> implements LoginCallBack {
- LoginStatus _loginStatus = LoginStatus.notSignIn;
- BuildContext _ctx;
- bool _isLoading = false;
- final formKey = new GlobalKey<FormState>();
- final scaffoldKey = new GlobalKey<ScaffoldState>();
-
- String _username, _password;
-
- LoginResponse _response;
-
- _LoginPageState() {
- _response = new LoginResponse(this);
- }
-
- void _submit() {
- final form = formKey.currentState;
-
- if (form.validate()) {
- setState(() {
- _isLoading = true;
- form.save();
- _response.doLogin(_username, _password);
- });
- }
- }
-
-
- void _showSnackBar(String text) {
- scaffoldKey.currentState.showSnackBar(new SnackBar(
- content: new Text(text),
- ));
- }
-
- var value;
- getPref() async {
- SharedPreferences preferences = await SharedPreferences.getInstance();
- setState(() {
- value = preferences.getInt("value");
-
- _loginStatus = value == 1 ? LoginStatus.signIn : LoginStatus.notSignIn;
- });
- }
-
- signOut() async {
- SharedPreferences preferences = await SharedPreferences.getInstance();
- setState(() {
- preferences.setInt("value", null);
- preferences.commit();
- _loginStatus = LoginStatus.notSignIn;
- });
- }
-
- @override
- void initState() {
- super.initState();
- getPref();
- }
-
- @override
- Widget build(BuildContext context) {
- switch (_loginStatus) {
- case LoginStatus.notSignIn:
- _ctx = context;
- var loginBtn = new RaisedButton(
- onPressed: _submit,
- child: new Text("Login"),
- color: Colors.green,
- );
- var loginForm = new Column(
- crossAxisAlignment: CrossAxisAlignment.center,
- children: <Widget>[
- new Form(
- key: formKey,
- child: new Column(
- children: <Widget>[
- new Padding(
- padding: const EdgeInsets.all(10.0),
- child: new TextFormField(
- onSaved: (val) => _username = val,
- decoration: new InputDecoration(labelText: "Username"),
- ),
- ),
- new Padding(
- padding: const EdgeInsets.all(10.0),
- child: new TextFormField(
- onSaved: (val) => _password = val,
- decoration: new InputDecoration(labelText: "Password"),
- ),
- )
- ],
- ),
- ),
- loginBtn
- ],
- );
-
- return new Scaffold(
- appBar: new AppBar(
- title: new Text("Login Page"),
- ),
- key: scaffoldKey,
- body: new Container(
- child: new Center(
- child: loginForm,
- ),
- ),
- );
- break;
- case LoginStatus.signIn:
- return HomeScreen(signOut);
- break;
- }
- }
-
- savePref(int value,String user, String pass) async {
- SharedPreferences preferences = await SharedPreferences.getInstance();
- setState(() {
- preferences.setInt("value", value);
- preferences.setString("user", user);
- preferences.setString("pass", pass);
- preferences.commit();
- });
- }
-
- @override
- void onLoginError(String error) {
- _showSnackBar(error);
- setState(() {
- _isLoading = false;
- });
- }
-
- @override
- void onLoginSuccess(User user) async {
-
- if(user != null){
- savePref(1,user.username, user.password);
- _loginStatus = LoginStatus.signIn;
- }else{
- _showSnackBar("Login Gagal, Silahkan Periksa Login Anda");
- setState(() {
- _isLoading = false;
- });
- }
-
- }
- }
The application can be run to show the output below,
For the complete source code you can look
Here.
Thank you for reading this article about Flutter Login With Database SQLite. I hope this article is useful for you.
Visit My Github about Flutter in Here.