Skip to content

Instantly share code, notes, and snippets.

@IkhwanSI13
Created March 6, 2021 15:28
Embed
What would you like to do?
Code setelah upgrade schema, Sqflite
class MahasiswaModel {
MahasiswaModel(
{this.nim, this.name, this.department, this.sks, this.address});
String nim;
String name;
String department;
int sks;
String address;
}
import 'package:explore_data/useCase/sqflite/MahasiswaModel.dart';
import 'package:explore_data/useCase/sqflite/OrganisasiModel.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
class MySqflite {
static final _databaseName = "MyDatabase.db";
static final _databaseV1 = 1;
static final _databaseV2 = 2;
///MAHASISWA
static final tableMahasiswa = 'mahasiswa';
static final columnNim = 'nim';
static final columnName = 'name';
static final columnDepartment = 'department';
static final columnSKS = 'sks';
static final columnAddress = 'alamat'; //new column
///ORGANISASI
static final tableOrganisasi = 'organisasi';
static final columnId = 'idOrganisasi';
static final columnOrganisasiNim = 'nim';
static final columnOrganisasiName = 'name';
// make this a singleton class
MySqflite._privateConstructor();
static final MySqflite instance = MySqflite._privateConstructor();
static Database _database;
Future<Database> get database async {
if (_database != null) return _database;
_database = await _initDatabase();
return _database;
}
_initDatabase() async {
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, _databaseName);
return await openDatabase(path, version: _databaseV2,
onCreate: (db, version) async {
var batch = db.batch();
_onCreateTableMahasiswaV2(batch);
_onCreateTableOrganisasiV2(batch);
await batch.commit();
}, onUpgrade: (db, oldVersion, newVersion) async {
var batch = db.batch();
if (oldVersion == _databaseV1) {
_onUpdateTableMahasiswaV1toV2(batch);
_onCreateTableOrganisasiV2(batch);
}
await batch.commit();
});
}
void _onCreateTableMahasiswaV2(Batch batch) async {
batch.execute('''
CREATE TABLE $tableMahasiswa (
$columnNim TEXT PRIMARY KEY,
$columnName TEXT,
$columnDepartment TEXT,
$columnSKS INTEGER,
$columnAddress TEXT
)
''');
}
void _onUpdateTableMahasiswaV1toV2(Batch batch) async {
batch.execute("ALTER TABLE $tableMahasiswa ADD COLUMN $columnAddress TEXT");
}
void _onCreateTableOrganisasiV2(Batch batch) async {
batch.execute('''
CREATE TABLE $tableOrganisasi (
$columnId INTEGER PRIMARY KEY AUTOINCREMENT,
$columnOrganisasiNim TEXT,
$columnOrganisasiName TEXT
)
''');
}
///TABLE MAHASISWA
Future<int> insertMahasiswa(MahasiswaModel model) async {
var row = {
columnNim: model.nim,
columnName: model.name,
columnDepartment: model.department,
columnSKS: model.sks,
columnAddress: model.address
};
Database db = await instance.database;
return await db.insert(tableMahasiswa, row);
}
Future<List<MahasiswaModel>> getMahasiswa() async {
Database db = await instance.database;
var allData = await db.rawQuery("SELECT * FROM $tableMahasiswa");
List<MahasiswaModel> result = [];
for (var data in allData) {
result.add(MahasiswaModel(
nim: data[columnNim],
name: data[columnName],
department: data[columnDepartment],
sks: int.parse(data[columnSKS].toString()),
address: data[columnAddress]));
}
return result;
}
Future<MahasiswaModel> getMahasiswaByNIM(String nim) async {
Database db = await instance.database;
var allData = await db.rawQuery(
"SELECT * FROM $tableMahasiswa WHERE $columnNim = $nim LIMIT 1");
if (allData.isNotEmpty) {
return MahasiswaModel(
nim: allData[0][columnNim],
name: allData[0][columnName],
department: allData[0][columnDepartment],
sks: int.parse(allData[0][columnSKS]),
address: allData[0][columnAddress]);
} else {
return null;
}
}
Future<int> updateMahasiswaDepartment(MahasiswaModel model) async {
Database db = await instance.database;
return await db.rawUpdate(
'UPDATE $tableMahasiswa SET $columnDepartment = ${model.department} '
'Where $columnNim = ${model.nim}');
}
Future<int> deleteMahasiswa(String nim) async {
Database db = await instance.database;
return await db
.rawDelete('DELETE FROM $tableMahasiswa Where $columnNim = $nim');
}
///TABLE ORGANISASI
Future<int> insertOrganisasi(String nim, String name) async {
var row = {columnOrganisasiNim: nim, columnOrganisasiName: name};
Database db = await instance.database;
return await db.insert(tableOrganisasi, row);
}
Future<List<OrganisasiModel>> getOrganisasi() async {
Database db = await instance.database;
var allData = await db.rawQuery("SELECT * FROM $tableOrganisasi");
if (allData.isNotEmpty) {
List<OrganisasiModel> result = [];
for (var data in allData) {
result.add(OrganisasiModel(
id: data[columnId],
nim: data[columnOrganisasiNim],
name: data[columnOrganisasiName]));
}
return result;
} else {
return [];
}
}
clearAllData() async {
Database db = await instance.database;
await db.rawQuery("DELETE FROM $tableMahasiswa");
await db.rawQuery("DELETE FROM $tableOrganisasi");
}
}
class OrganisasiModel {
OrganisasiModel({this.id, this.nim, this.name});
String id;
String nim;
String name;
}
import 'package:explore_data/useCase/sqflite/MahasiswaModel.dart';
import 'package:explore_data/useCase/sqflite/MySqlflite.dart';
import 'package:flutter/material.dart';
class SqfliteActivity extends StatefulWidget {
@override
State<StatefulWidget> createState() => SqfliteActivityState();
}
class SqfliteActivityState extends State<SqfliteActivity> {
final keyFormMahasiswa = GlobalKey<FormState>();
TextEditingController controllerNim = TextEditingController();
TextEditingController controllerName = TextEditingController();
TextEditingController controllerDepartment = TextEditingController();
TextEditingController controllerSks = TextEditingController();
TextEditingController controllerAddress = TextEditingController();
String nim = "";
String name = "";
String department = "";
int sks = 0;
String address = "";
List<MahasiswaModel> mahasiswa = [];
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
mahasiswa = await MySqflite.instance.getMahasiswa();
setState(() {});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
margin: EdgeInsets.only(top: 36, left: 24, bottom: 4),
child: Text("Input Mahasiswa",
style: TextStyle(fontWeight: FontWeight.bold)),
),
Form(
key: keyFormMahasiswa,
child: Container(
margin: EdgeInsets.only(left: 24, right: 24),
child: Column(
children: [
TextFormField(
controller: controllerNim,
decoration: InputDecoration(hintText: "NIM"),
validator: (value) => _onValidateText(value),
keyboardType: TextInputType.number,
onSaved: (value) => nim = value,
),
TextFormField(
controller: controllerName,
decoration: InputDecoration(hintText: "Nama"),
validator: (value) => _onValidateText(value),
onSaved: (value) => name = value,
),
TextFormField(
controller: controllerDepartment,
decoration: InputDecoration(hintText: "Jurusan"),
validator: (value) => _onValidateText(value),
onSaved: (value) => department = value,
),
TextFormField(
controller: controllerSks,
decoration: InputDecoration(hintText: "SKS"),
validator: (value) => _onValidateText(value),
keyboardType: TextInputType.number,
onSaved: (value) => sks = int.parse(value),
),
TextFormField(
controller: controllerAddress,
decoration: InputDecoration(hintText: "Address"),
validator: (value) => _onValidateText(value),
onSaved: (value) => address = value,
),
],
),
),
),
Container(
margin: EdgeInsets.only(left: 24, right: 24),
child: RaisedButton(
onPressed: () {
_onSaveMahasiswa();
},
child: Text("Simpan"),
),
),
Container(
margin: EdgeInsets.only(top: 24, left: 24, bottom: 4),
child: Text("Data Mahasiswa",
style: TextStyle(fontWeight: FontWeight.bold)),
),
Expanded(
child: ListView.builder(
itemCount: mahasiswa.length,
padding: EdgeInsets.fromLTRB(24, 0, 24, 8),
itemBuilder: (BuildContext context, int index) {
var value = mahasiswa[index];
return Container(
margin: EdgeInsets.only(bottom: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Text("Nim: ${value.nim}"),
Text("Name: ${value.name}"),
Text("Department: ${value.department}"),
Text("SKS: ${value.sks}"),
Text("Address: ${value.address}"),
],
),
);
}))
],
));
}
String _onValidateText(String value) {
if (value.isEmpty) return 'Tidak boleh kosong';
return null;
}
_onSaveMahasiswa() async {
FocusScope.of(context).requestFocus(new FocusNode());
if (keyFormMahasiswa.currentState.validate()) {
keyFormMahasiswa.currentState.save();
controllerNim.text = "";
controllerName.text = "";
controllerDepartment.text = "";
controllerSks.text = "";
controllerAddress.text = "";
await MySqflite.instance.insertMahasiswa(MahasiswaModel(
nim: nim,
name: name,
department: department,
sks: sks,
address: address));
mahasiswa = await MySqflite.instance.getMahasiswa();
setState(() {});
}
}
}
@ArfanAdamNasution
Copy link

Mau tanya bg, main.dart = Mysqflite.dart ya?

@IkhwanSI13
Copy link
Author

Mau tanya bg, main.dart = Mysqflite.dart ya?

Bukan bg, bisa dijalankan dengan
runApp(SqfliteActivity());
di main.dart

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment