Browse Source

Perbaikan: pengaturan IpOrDomain tersimpan sqflite

master
unknown 12 months ago
parent
commit
6bed80af1c
  1. 26
      lib/connection/connection.dart
  2. 2
      lib/main.dart
  3. 9
      lib/migrations/databasehelper.dart
  4. 18
      lib/models/ip_domain_model.dart
  5. 101
      lib/pages/login/controller/loginController.dart
  6. 103
      lib/pages/login/sign_in_page.dart

26
lib/connection/connection.dart

@ -1,13 +1,11 @@
import 'package:shared_preferences/shared_preferences.dart'; import '../pages/login/controller/loginController.dart'; // Sesuaikan path dengan struktur proyek Anda
import 'package:shared_preferences/shared_preferences.dart';
import '../pages/sign_in_page.dart';
import 'package:path_provider/path_provider.dart';
Future<String> getBaseUrl() async { Future<String> getBaseUrl() async {
try { try {
String savedValue = await getSavedValue(); List ipDomainList = await ControllerLogin().fetchData();
if (ipDomainList.isNotEmpty) {
String savedValue = ipDomainList.first['ipOrDomain'] ?? '';
// Check if savedValue is a domain, IP with or without port // Check if savedValue is a domain, IP with or without port
String baseUrl; String baseUrl;
@ -15,7 +13,8 @@ Future<String> getBaseUrl() async {
if (savedValue.contains(':')) { if (savedValue.contains(':')) {
// If savedValue contains a colon, assume it's an IP with port // If savedValue contains a colon, assume it's an IP with port
baseUrl = 'http://$savedValue/api/v1'; baseUrl = 'http://$savedValue/api/v1';
} else if (RegExp(r'^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$').hasMatch(savedValue)) { } else if (RegExp(r'^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
.hasMatch(savedValue)) {
// If savedValue matches the domain pattern, assume it's a domain // If savedValue matches the domain pattern, assume it's a domain
baseUrl = 'https://$savedValue/api/v1'; baseUrl = 'https://$savedValue/api/v1';
} else { } else {
@ -24,9 +23,14 @@ Future<String> getBaseUrl() async {
} }
return baseUrl; return baseUrl;
} else {
// Handle jika tidak ada data di database (misalnya, berikan nilai default atau tampilkan pesan kesalahan)
print('No data found in database.');
return ''; // Atau berikan nilai default lainnya sesuai kebutuhan
}
} catch (e) { } catch (e) {
// Error handling // Handle kesalahan pembacaan dari database
print('Error reading SharedPreferences: $e'); print('Error reading data from database: $e');
return ''; // Or any other default value in case of an error return ''; // Atau berikan nilai default lainnya sesuai kebutuhan
} }
} }

2
lib/main.dart

@ -12,7 +12,7 @@ import 'pages/peminjaman_barang/create.dart';
import 'pages/peminjaman_barang/show.dart'; import 'pages/peminjaman_barang/show.dart';
import 'pages/pengembalian_barang/edit.dart'; import 'pages/pengembalian_barang/edit.dart';
import 'pages/pengembalian_barang/index.dart'; import 'pages/pengembalian_barang/index.dart';
import 'pages/sign_in_page.dart'; import 'pages/login/sign_in_page.dart';
import 'pages/splash_page.dart'; import 'pages/splash_page.dart';
import 'pages/transfer_peti/index.dart'; import 'pages/transfer_peti/index.dart';
import 'providers/asset_status_provider.dart'; import 'providers/asset_status_provider.dart';

9
lib/migrations/databasehelper.dart

@ -24,7 +24,7 @@ class SqfliteDatabaseHelper {
// static final assetLocalTable = 'asset_statuses_local'; // static final assetLocalTable = 'asset_statuses_local';
static final peminjamanTable = 'peminjamans'; static final peminjamanTable = 'peminjamans';
static final temporaryPeminjamanTable = 'temporary_peminjamans'; static final ipDomainTable = 'ipdomain';
static final pengembalianTable = 'pengembalians'; static final pengembalianTable = 'pengembalians';
@ -65,6 +65,13 @@ class SqfliteDatabaseHelper {
print(dbPath); print(dbPath);
var openDb = await openDatabase(dbPath, version: _version, var openDb = await openDatabase(dbPath, version: _version,
onCreate: (Database db, int version) async { onCreate: (Database db, int version) async {
await db.execute("""
CREATE TABLE $ipDomainTable (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ipOrDomain TEXT
);
""");
await db.execute(""" await db.execute("""
CREATE TABLE $peminjamanTable ( CREATE TABLE $peminjamanTable (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,

18
lib/models/ip_domain_model.dart

@ -0,0 +1,18 @@
class IpDomain {
int? id;
String? ipOrDomain;
IpDomain({this.id, this.ipOrDomain});
factory IpDomain.fromJson(Map<String, dynamic> json) {
return IpDomain(
id: json['id'] ? json['id'] : 0,
ipOrDomain: json['ipOrDomain'] ? json['ipOrDomain'] : '',
);
}
Map<String, dynamic> toJson() => {
'id': id,
'ipOrDomain': ipOrDomain,
};
}

101
lib/pages/login/controller/loginController.dart

@ -0,0 +1,101 @@
import 'package:sqflite/sqflite.dart';
import '../../../migrations/databasehelper.dart';
import '../../../models/ip_domain_model.dart';
class ControllerLogin {
final conn = SqfliteDatabaseHelper.instance;
Future<int> addData(IpDomain ipDomain) async {
var dbclient = await conn.db;
int result = 0; // Provide an initial value
try {
result = await dbclient!
.insert(SqfliteDatabaseHelper.ipDomainTable, ipDomain.toJson());
} catch (e) {
print(e.toString());
}
return result;
}
Future<int> updateData(IpDomain ipDomain) async {
var dbclient = await conn.db;
late int result;
try {
result = await dbclient!.update(
SqfliteDatabaseHelper.ipDomainTable,
ipDomain.toJson(),
where: 'id=?',
whereArgs: [ipDomain.id],
);
} catch (e) {
print(e.toString());
}
return result;
}
Future<List> fetchData() async {
var dbclient = await conn.db;
List userList = [];
try {
List<Map<String, dynamic>> maps = await dbclient!
.query(SqfliteDatabaseHelper.ipDomainTable, orderBy: 'id DESC');
for (var item in maps) {
userList.add(item);
}
} catch (e) {
print(e.toString());
}
return userList;
}
Future<List<IpDomain>> fetchDataId() async {
var dbclient = await conn.db;
List<IpDomain> ipDomainList = [];
try {
List<Map<String, dynamic>> maps = await dbclient!
.query(SqfliteDatabaseHelper.ipDomainTable, orderBy: 'id DESC');
for (var item in maps) {
ipDomainList.add(IpDomain.fromJson(item));
}
} catch (e) {
print(e.toString());
}
return ipDomainList;
}
// Future<void> deleteAllData() async {
// var dbClient = await conn.db;
// await dbClient!.delete(SqfliteDatabaseHelper.ipDomainTable);
// }
Future<void> resetAutoIncrement() async {
var dbClient = await conn.db;
await dbClient!.execute(
'DELETE FROM SQLITE_SEQUENCE WHERE NAME = "${SqfliteDatabaseHelper.ipDomainTable}"');
}
Future<void> deleteAllData() async {
var dbClient = await conn.db;
// Hapus semua data dari tabel
await dbClient!.delete(SqfliteDatabaseHelper.ipDomainTable);
// Reset auto-increment to 1
await resetAutoIncrement();
}
Future<void> addAllData(List<IpDomain> ipDomainList) async {
var dbclient = await conn.db;
Batch batch = dbclient!.batch();
for (var ipDomain in ipDomainList) {
batch.insert(
SqfliteDatabaseHelper.ipDomainTable,
ipDomain.toJson(),
);
}
await batch.commit();
}
}

103
lib/pages/sign_in_page.dart → lib/pages/login/sign_in_page.dart

@ -5,9 +5,11 @@ import 'package:flutter/services.dart';
import 'package:siopas/theme.dart'; import 'package:siopas/theme.dart';
import '../models/user_model.dart'; import '../../models/ip_domain_model.dart';
import '../providers/auth_provider.dart'; import '../../models/user_model.dart';
import '../widget/loading_button.dart'; import '../../providers/auth_provider.dart';
import '../../widget/loading_button.dart';
import 'controller/loginController.dart';
class SignInPage extends StatefulWidget { class SignInPage extends StatefulWidget {
@override @override
@ -358,19 +360,28 @@ class SettingsModal extends StatefulWidget {
} }
class _SettingsModalState extends State<SettingsModal> { class _SettingsModalState extends State<SettingsModal> {
TextEditingController inputController = TextEditingController(); TextEditingController ipDomainController = TextEditingController();
List<dynamic>? getIpDomainList;
bool loading = true;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
// Load saved IP Address or Port when the modal is initialized ipDomainList();
loadSettings();
} }
void loadSettings() async { Future ipDomainList() async {
String savedValue = await getSavedValue(); await ControllerLogin().fetchData().then((value) {
setState(() { setState(() {
inputController.text = savedValue; getIpDomainList = value;
loading = false;
// Set nilai ipDomainController dengan ID terbaru jika ada data
if (getIpDomainList != null && getIpDomainList!.isNotEmpty) {
ipDomainController.text =
getIpDomainList![0]['ipOrDomain'].toString();
}
});
}); });
} }
@ -389,49 +400,59 @@ class _SettingsModalState extends State<SettingsModal> {
), ),
], ],
), ),
actions: [
ElevatedButton(
onPressed: () async {
IpDomain ipDomainModel = IpDomain(
id: null,
ipOrDomain: ipDomainController.text,
);
// Panggil fungsi deleteAllData untuk menghapus data sebelumnya
await ControllerLogin().deleteAllData();
// Panggil fungsi addData untuk menyimpan data baru
int result = await ControllerLogin().addData(ipDomainModel);
if (result > 0) {
print("Success");
// Gunakan setState untuk memicu pembaruan widget setelah data disimpan
setState(() {
loading = true; // Sinyal bahwa sedang memuat
});
// Panggil fungsi ipDomainList untuk mengambil ulang data
await ipDomainList();
// Setelah data diambil ulang, nonaktifkan loading
setState(() {
loading = false;
});
// Setelah data disimpan dan diambil ulang, lakukan Navigator.pop
Navigator.pop(context); // Kembali ke halaman sebelumnya
} else {
print("Failed");
}
},
child: Text("Save"),
),
],
content: Column( content: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
TextFormField( TextFormField(
controller: inputController, controller: ipDomainController,
inputFormatters: [ inputFormatters: [
FilteringTextInputFormatter.allow( FilteringTextInputFormatter.allow(
RegExp(r'[a-zA-Z0-9@#$%^&*()_+={}|\[\]\\:;"<>,.?/~`-]')) RegExp(r'[a-zA-Z0-9@#$%^&*()_+={}|\[\]\\:;"<>,.?/~`-]'),
),
], ],
decoration: InputDecoration(labelText: 'Domain atau IP:Port'), decoration: InputDecoration(labelText: 'Domain atau IP:Port'),
), ),
], ],
), ),
actions: [
ElevatedButton(
onPressed: () {
// Save value to SharedPreferences
saveSettings(inputController.text);
Navigator.of(context).pop(); // Close the modal
},
child: Text('Simpan'),
),
],
); );
} }
Future<void> saveSettings(String value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('savedValue', value);
// Print the saved data
print('Value saved: $value');
}
Future<void> clearSettings() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove('savedValue');
print('Value cleared');
}
}
Future<String> getSavedValue() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String savedValue = prefs.getString('savedValue') ?? '';
return savedValue;
} }
Loading…
Cancel
Save