Skip to content

Instantly share code, notes, and snippets.

@ostertagi
Forked from Andrious/employee.dart
Created September 25, 2018 08:41
Show Gist options
  • Select an option

  • Save ostertagi/4c33863a54032be170021400b7878710 to your computer and use it in GitHub Desktop.

Select an option

Save ostertagi/4c33863a54032be170021400b7878710 to your computer and use it in GitHub Desktop.
SQFlite Database in Flutter Example: main.dart, employee.dart
import 'dart:async';
import 'package:sqflite/sqflite.dart';
import 'package:dbutils/sqllitedb.dart';
class Employee extends DBInterface{
factory Employee(){
if(_this == null) _this = Employee._getInstance();
return _this;
}
/// Make only one instance of this class.
static Employee _this;
Employee._getInstance(): super();
@override
get name => 'testing.db';
@override
get version => 1;
@override
Future onCreate(Database db, int version) async {
await db.execute("""
CREATE TABLE Employee(
id INTEGER PRIMARY KEY
,firstname TEXT
,lastname TEXT
,mobileno TEXT
,emailId TEXT
)
""");
}
void save(String table){
saveRec(table);
}
Future<List<Map>> getEmployees() async {
return await this.rawQuery('SELECT * FROM Employee');
}
}
import 'dart:async';
import 'package:flutter/material.dart';
import 'employee.dart';
//Future<List<Map<String, dynamic>>>
Future<List<Map>> fetchEmployeesFromDatabase() async {
return Employee().getEmployees();
}
class MyEmployeeList extends StatefulWidget {
@override
MyEmployeeListPageState createState() => new MyEmployeeListPageState();
}
class MyEmployeeListPageState extends State<MyEmployeeList> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Employee List'),
),
body: new Container(
padding: new EdgeInsets.all(16.0),
child: new FutureBuilder<List<Map>>(
future: fetchEmployeesFromDatabase(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return new ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Text(snapshot.data[index]['firstname'],
style: new TextStyle(
fontWeight: FontWeight.bold, fontSize: 18.0)),
new Text(snapshot.data[index]['lastname'],
style: new TextStyle(
fontWeight: FontWeight.bold, fontSize: 14.0)),
new Divider()
]);
});
} else if (snapshot.hasError) {
return new Text("${snapshot.error}");
}
return new Container(alignment: AlignmentDirectional.center,child: new CircularProgressIndicator(),);
},
),
),
);
}
}
import 'dart:async';
import 'package:flutter/material.dart';
import 'employee.dart';
import 'employeelist.dart';
void main(){
/// The default is to dump the error to the console.
/// Instead, a custom function is called.
FlutterError.onError = (FlutterErrorDetails details) async {
await _reportError(details);
};
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'SQFLite DataBase Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Employee _db = Employee();
final scaffoldKey = new GlobalKey<ScaffoldState>();
final formKey = new GlobalKey<FormState>();
@override
initState(){
super.initState();
_db.init();
}
@override
void dispose() {
_db.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
key: scaffoldKey,
appBar: new AppBar(
title: new Text('Saving Employee'),
actions: <Widget>[
new IconButton(
icon: const Icon(Icons.view_list),
tooltip: 'Next choice',
onPressed: () {
navigateToEmployeeList();
},
),
]
),
body: new Padding(
padding: const EdgeInsets.all(16.0),
child: new Form(
key: formKey,
child: new Column(
children: [
new TextFormField(
keyboardType: TextInputType.text,
decoration: new InputDecoration(labelText: 'First Name'),
validator: (val) =>
val.length == 0 ?"Enter FirstName" : null,
onSaved: (val) => _db.values['Employee']['firstname'] = val,
),
new TextFormField(
keyboardType: TextInputType.text,
decoration: new InputDecoration(labelText: 'Last Name'),
validator: (val) =>
val.length ==0 ? 'Enter LastName' : null,
onSaved: (val) => _db.values['Employee']['lastname'] = val,
),
new TextFormField(
keyboardType: TextInputType.phone,
decoration: new InputDecoration(labelText: 'Mobile No'),
validator: (val) =>
val.length ==0 ? 'Enter Mobile No' : null,
onSaved: (val) => _db.values['Employee']['mobileno'] = val,
),
new TextFormField(
keyboardType: TextInputType.emailAddress,
decoration: new InputDecoration(labelText: 'Email Id'),
validator: (val) =>
val.length ==0 ? 'Enter Email Id' : null,
onSaved: (val) =>_db.values['Employee']['emailId'] = val,
),
new Container(margin: const EdgeInsets.only(top: 10.0),child: new RaisedButton(onPressed: _submit,
child: new Text('Login'),),)
],
),
),
),
);
}
void _submit() {
if (this.formKey.currentState.validate()) {
formKey.currentState.save();
}else{
return null;
}
_db.save('Employee');
_showSnackBar("Data saved successfully");
}
void _showSnackBar(String text) {
scaffoldKey.currentState
.showSnackBar(new SnackBar(content: new Text(text)));
}
void navigateToEmployeeList(){
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new MyEmployeeList()),
);
}
}
/// Reports [error] along with its [stackTrace]
Future<Null> _reportError(FlutterErrorDetails details) async {
// details.exception, details.stack
FlutterError.dumpErrorToConsole(details);
}
dependencies:
flutter:
sdk: flutter
dbutils:
git:
url: git://github.com/AndriousSolutions/dbutils.git
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment