This article will creating a simple application using Flutter that is integrated with the SQLite database. You can try this tutorial about flutter login 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:
- Invoke View > Command Palette.
- Type “flutter”, and select the Flutter: New Project.
- Enter a project name, such as myapp, and press Enter.
- Create or select the parent directory for the new project folder.
- Wait the process for project creation to complete and the main.dart file to appear.
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 should look something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
name: login description: A new Flutter prject. # 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://developer.android.com/studio/publish/versioning # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. # Read more about iOS versioning at # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html 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 dev_dependencies: flutter_test: sdk: flutter # For information on the generic Dart part of this file, see the # following page: https://www.dartlang.org/tools/pub/pubspec # 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://flutter.io/assets-and-images/#resolution-aware. # For details regarding adding assets from package dependencies, see # https://flutter.io/assets-and-images/#from-packages # 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://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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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 like that :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
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"); // Only copy if the database doesn't exist //if (FileSystemEntity.typeSync(path) == FileSystemEntityType.notFound){ // Load database from asset and copy ByteData data = await rootBundle.load(join('data', 'flutter.db')); List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); // Save copied asset to documents 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 user login. The file login_ctr.dart like below :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import 'package:login/models/user.dart'; import 'dart:async'; import 'package:login/data/database_helper.dart'; class LoginCtr { DatabaseHelper con = new DatabaseHelper(); //insertion Future<int> saveUser(User user) async { var dbClient = await con.db; int res = await dbClient.insert("User", user.toMap()); return res; } //deletion 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 :
login_response.dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
import 'package:flutter/material.dart'; import 'package:login/models/user.dart'; import 'package:login/services/response/login_response.dart'; class LoginPage extends StatefulWidget { @override _LoginPageState createState() => new _LoginPageState(); } class _LoginPageState extends State<LoginPage> implements LoginCallBack { 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), )); } @override Widget build(BuildContext context) { _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, ), ), ); } @override void onLoginError(String error) { // TODO: implement onLoginError _showSnackBar(error); setState(() { _isLoading = false; }); } @override void onLoginSuccess(User user) async { if(user != null){ Navigator.of(context).pushNamed("/home"); }else{ // TODO: implement onLoginSuccess _showSnackBar("Login Gagal, Silahkan Periksa Login Anda"); setState(() { _isLoading = false; }); } } } |
The application can be run to show output below :
For complete source code you can see in 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