Flutter Login With Database SQLite

This article will create a simple application using Flutter that is integrated with the SQLite database. You can try this tutorial example step by step after we install flutter  in this section How to install flutter step by step on windows.
 
First, we must create a project using Visual Studio Code software. Here's how to create a new project using Visual Studio Code:
  1. Invoke View > Command Palette.
  2. Type “flutter”, and select the Flutter: New Project.
  3. Enter a project name, such as myapp, and press Enter.
  4. Create or select the parent directory for the new project folder.
  5. Wait the process for project creation to complete and the main.dart file to appear.
Flutter Login With Database SQLite
 
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.
 
Flutter Login With Database SQLite
 
Edit file pubspec.yaml in your directory and it  should look something like this:
  1. name: login  
  2. description: A new Flutter project.  
  3.   
  4. # The following defines the version and build number for your application.  
  5. # A version number is three numbers separated by dots, like 1.2.43  
  6. # followed by an optional build number separated by a +.  
  7. # Both the version and the builder number may be overridden in flutter  
  8. # build by specifying --build-name and --build-number, respectively.  
  9. # In Android, build-name is used as versionName while build-number used as versionCode.  
  10. # Read more about Android versioning at https://developer.android.com/studio/publish/versioning  
  11. # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.  
  12. # Read more about iOS versioning at  
  13. # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html  
  14. version: 1.0.0+1  
  15.   
  16. environment:  
  17.   sdk: ">=2.1.0 <3.0.0"  
  18.   
  19. dependencies:  
  20.   flutter:  
  21.     sdk: flutter  
  22.   
  23.   # The following adds the Cupertino Icons font to your application.  
  24.   # Use with the CupertinoIcons class for iOS style icons.  
  25.   cupertino_icons: ^0.1.2  
  26.   sqflite: any  
  27.   path_provider: ^0.4.0  
  28.   shared_preferences: ^0.5.4  
  29.     
  30. dev_dependencies:  
  31.   flutter_test:  
  32.     sdk: flutter  
  33.   
  34. # For information on the generic Dart part of this file, see the  
  35. # following page: https://www.dartlang.org/tools/pub/pubspec  
  36.   
  37. # The following section is specific to Flutter.  
  38. flutter:  
  39.   
  40.   # The following line ensures that the Material Icons font is  
  41.   # included with your application, so that you can use the icons in  
  42.   # the material Icons class.  
  43.   uses-material-design: true  
  44.   
  45.   assets:  
  46.     - data/flutter.db  
  47.   # To add assets to your application, add an assets section, like this:  
  48.   # assets:  
  49.   #  - images/a_dot_burr.jpeg  
  50.   #  - images/a_dot_ham.jpeg  
  51.   
  52.   # An image asset can refer to one or more resolution-specific "variants", see  
  53.   # https://flutter.io/assets-and-images/#resolution-aware.  
  54.   
  55.   # For details regarding adding assets from package dependencies, see  
  56.   # https://flutter.io/assets-and-images/#from-packages  
  57.   
  58.   # To add custom fonts to your application, add a fonts section here,  
  59.   # in this "flutter" section. Each entry in this list should have a  
  60.   # "family" key with the font family name, and a "fonts" key with a  
  61.   # list giving the asset and other descriptors for the font. For  
  62.   # example:  
  63.   # fonts:  
  64.   #   - family: Schyler  
  65.   #     fonts:  
  66.   #       - asset: fonts/Schyler-Regular.ttf  
  67.   #       - asset: fonts/Schyler-Italic.ttf  
  68.   #         style: italic  
  69.   #   - family: Trajan Pro  
  70.   #     fonts:  
  71.   #       - asset: fonts/TrajanPro.ttf  
  72.   #       - asset: fonts/TrajanPro_Bold.ttf  
  73.   #         weight: 700  
  74.   #  
  75.   # For details regarding fonts from package dependencies,  
  76.   # see https://flutter.io/custom-fonts/#from-packages 
We’re going to need to create a user.dart in directory [projectname]/lib/models which helps us manage a user's data.
  1. class User {  
  2.   int _id;  
  3.   String _username;  
  4.   String _password;  
  5.   
  6.   User(this._username, this._password);  
  7.   
  8.   User.fromMap(dynamic obj) {  
  9.     this._username = obj['username'];  
  10.     this._password = obj['password'];  
  11.   }  
  12.   
  13.   String get username => _username;  
  14.   String get password => _password;  
  15.   
  16.   Map<String, dynamic> toMap() {  
  17.     var map = new Map<String, dynamic>();  
  18.     map["username"] = _username;  
  19.     map["password"] = _password;  
  20.     return map;  
  21.   }  

And to database_helper.dart:
  1. import 'dart:io';  
  2. import 'dart:typed_data';  
  3. import 'package:flutter/services.dart';  
  4. import 'package:login/models/user.dart';  
  5. import 'package:path/path.dart';  
  6. import 'dart:async';  
  7. import 'package:path_provider/path_provider.dart';  
  8. import 'package:sqflite/sqflite.dart';  
  9.   
  10. class DatabaseHelper {  
  11.   static final DatabaseHelper _instance = new DatabaseHelper.internal();  
  12.   factory DatabaseHelper() => _instance;  
  13.   
  14.   static Database _db;  
  15.   
  16.   Future<Database> get db async {  
  17.     if (_db != null) {  
  18.       return _db;  
  19.     }  
  20.     _db = await initDb();  
  21.     return _db;  
  22.   }  
  23.   
  24.   DatabaseHelper.internal();  
  25.   
  26.   initDb() async {  
  27.     Directory documentDirectory = await getApplicationDocumentsDirectory();  
  28.     String path = join(documentDirectory.path, "data_flutter.db");  
  29.       
  30.     // Only copy if the database doesn't exist  
  31.     //if (FileSystemEntity.typeSync(path) == FileSystemEntityType.notFound){  
  32.       // Load database from asset and copy  
  33.       ByteData data = await rootBundle.load(join('data''flutter.db'));  
  34.       List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);  
  35.   
  36.       // Save copied asset to documents  
  37.       await new File(path).writeAsBytes(bytes);  
  38.     //}  
  39.   
  40.     var ourDb = await openDatabase(path);  
  41.     return ourDb;  
  42.   }  
  43. }  
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,
  1. import 'package:login/models/user.dart';  
  2. import 'dart:async';  
  3. import 'package:login/data/database_helper.dart';  
  4.   
  5. class LoginCtr {  
  6. DatabaseHelper con = new DatabaseHelper();  
  7.   
  8. //insertion  
  9.   Future<int> saveUser(User user) async {  
  10.     var dbClient = await con.db;  
  11.     int res = await dbClient.insert("User", user.toMap());  
  12.     return res;  
  13.   }  
  14.   
  15.   //deletion  
  16.   Future<int> deleteUser(User user) async {  
  17.     var dbClient = await con.db;  
  18.     int res = await dbClient.delete("User");  
  19.     return res;  
  20.   }  
  21.   
  22.   Future<User> getLogin(String user, String password) async {  
  23.     var dbClient = await con.db;  
  24.     var res = await dbClient.rawQuery("SELECT * FROM user WHERE username = '$user' and password = '$password'");  
  25.       
  26.     if (res.length > 0) {  
  27.       return new User.fromMap(res.first);  
  28.     }  
  29.   
  30.     return null;  
  31.   }  
  32.   
  33.   Future<List<User>> getAllUser() async {  
  34.     var dbClient = await con.db;  
  35.     var res = await dbClient.query("user");  
  36.       
  37.     List<User> list =  
  38.         res.isNotEmpty ? res.map((c) => User.fromMap(c)).toList() : null;  
  39.   
  40.     return list;  
  41.   }  

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.dartlogin_request.dart like below,
 
login_response.dart 
  1. import 'package:login/services/request/login_request.dart';  
  2. import 'package:login/models/user.dart';  
  3.   
  4. abstract class LoginCallBack {  
  5.   void onLoginSuccess(User user);  
  6.   void onLoginError(String error);  
  7. }  
  8.   
  9. class LoginResponse {  
  10.   LoginCallBack _callBack;  
  11.   LoginRequest loginRequest = new LoginRequest();  
  12.   LoginResponse(this._callBack);  
  13.   
  14.   doLogin(String username, String password) {  
  15.     loginRequest  
  16.         .getLogin(username, password)  
  17.         .then((user) => _callBack.onLoginSuccess(user))  
  18.         .catchError((onError) => _callBack.onLoginError(onError.toString()));  
  19.   }   

login_request.dart
  1. import 'dart:async';  
  2.   
  3. import 'package:login/models/user.dart';  
  4. import 'package:login/data/CtrQuery/login_ctr.dart';  
  5.   
  6. class LoginRequest {  
  7.   LoginCtr con = new LoginCtr();  
  8.   
  9.  Future<User> getLogin(String username, String password) {  
  10.     var result = con.getLogin(username,password);  
  11.     return result;  
  12.   }  

Later, we create login_screen.dart
  1. import 'package:flutter/material.dart';  
  2. import 'package:login/models/user.dart';  
  3. import 'package:login/screen/home_page.dart';  
  4. import 'package:login/services/response/login_response.dart';  
  5. import 'package:shared_preferences/shared_preferences.dart';  
  6.   
  7. class LoginPage extends StatefulWidget {  
  8.   @override  
  9.   _LoginPageState createState() => new _LoginPageState();  
  10. }  
  11.   
  12. enum LoginStatus { notSignIn, signIn }  
  13.   
  14. class _LoginPageState extends State<LoginPage> implements LoginCallBack {  
  15.   LoginStatus _loginStatus = LoginStatus.notSignIn;  
  16.   BuildContext _ctx;  
  17.   bool _isLoading = false;  
  18.   final formKey = new GlobalKey<FormState>();  
  19.   final scaffoldKey = new GlobalKey<ScaffoldState>();  
  20.     
  21.   String _username, _password;  
  22.   
  23.   LoginResponse _response;  
  24.   
  25.   _LoginPageState() {  
  26.     _response = new LoginResponse(this);  
  27.   }  
  28.   
  29.   void _submit() {  
  30.     final form = formKey.currentState;  
  31.   
  32.     if (form.validate()) {  
  33.       setState(() {  
  34.         _isLoading = true;  
  35.         form.save();  
  36.         _response.doLogin(_username, _password);  
  37.       });  
  38.     }  
  39.   }  
  40.     
  41.   
  42.   void _showSnackBar(String text) {  
  43.     scaffoldKey.currentState.showSnackBar(new SnackBar(  
  44.       content: new Text(text),  
  45.     ));  
  46.   }  
  47.   
  48.   var value;  
  49.  getPref() async {  
  50.    SharedPreferences preferences = await SharedPreferences.getInstance();  
  51.    setState(() {  
  52.      value = preferences.getInt("value");  
  53.   
  54.      _loginStatus = value == 1 ? LoginStatus.signIn : LoginStatus.notSignIn;  
  55.    });  
  56.  }  
  57.   
  58.    signOut() async {  
  59.     SharedPreferences preferences = await SharedPreferences.getInstance();  
  60.     setState(() {  
  61.       preferences.setInt("value"null);  
  62.       preferences.commit();  
  63.       _loginStatus = LoginStatus.notSignIn;  
  64.     });  
  65.   }  
  66.   
  67.   @override  
  68.   void initState() {  
  69.     super.initState();  
  70.     getPref();  
  71.   }  
  72.   
  73.   @override  
  74.   Widget build(BuildContext context) {  
  75.       switch (_loginStatus) {  
  76.         case LoginStatus.notSignIn:  
  77.           _ctx = context;  
  78.           var loginBtn = new RaisedButton(  
  79.             onPressed: _submit,  
  80.             child: new Text("Login"),  
  81.             color: Colors.green,  
  82.           );  
  83.           var loginForm = new Column(  
  84.             crossAxisAlignment: CrossAxisAlignment.center,  
  85.             children: <Widget>[  
  86.               new Form(  
  87.                 key: formKey,  
  88.                 child: new Column(  
  89.                   children: <Widget>[  
  90.                     new Padding(  
  91.                       padding: const EdgeInsets.all(10.0),  
  92.                       child: new TextFormField(  
  93.                         onSaved: (val) => _username = val,  
  94.                         decoration: new InputDecoration(labelText: "Username"),  
  95.                       ),  
  96.                     ),  
  97.                     new Padding(  
  98.                       padding: const EdgeInsets.all(10.0),  
  99.                       child: new TextFormField(  
  100.                         onSaved: (val) => _password = val,  
  101.                         decoration: new InputDecoration(labelText: "Password"),  
  102.                       ),  
  103.                     )  
  104.                   ],  
  105.                 ),  
  106.               ),  
  107.               loginBtn  
  108.             ],  
  109.           );  
  110.   
  111.            return new Scaffold(  
  112.             appBar: new AppBar(  
  113.               title: new Text("Login Page"),  
  114.             ),  
  115.             key: scaffoldKey,  
  116.             body: new Container(  
  117.               child: new Center(  
  118.                 child: loginForm,  
  119.               ),  
  120.             ),  
  121.           );  
  122.           break;  
  123.         case LoginStatus.signIn:  
  124.           return HomeScreen(signOut);  
  125.           break;  
  126.     }  
  127.   }  
  128.   
  129.   savePref(int value,String user, String pass) async {  
  130.     SharedPreferences preferences = await SharedPreferences.getInstance();  
  131.     setState(() {  
  132.       preferences.setInt("value", value);  
  133.       preferences.setString("user", user);  
  134.       preferences.setString("pass", pass);  
  135.       preferences.commit();  
  136.     });  
  137.   }  
  138.   
  139.   @override  
  140.   void onLoginError(String error) {  
  141.     _showSnackBar(error);  
  142.     setState(() {  
  143.       _isLoading = false;  
  144.     });  
  145.   }  
  146.   
  147.   @override  
  148.   void onLoginSuccess(User user) async {      
  149.   
  150.     if(user != null){  
  151.       savePref(1,user.username, user.password);  
  152.       _loginStatus = LoginStatus.signIn;  
  153.     }else{  
  154.       _showSnackBar("Login Gagal, Silahkan Periksa Login Anda");  
  155.       setState(() {  
  156.         _isLoading = false;  
  157.       });  
  158.     }  
  159.       
  160.   }  

The application can be run to show the output below,
 
Flutter Login With Database SQLite
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.


Similar Articles