91 lines
3.1 KiB
Dart
91 lines
3.1 KiB
Dart
import 'package:cloud_firestore/cloud_firestore.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:tugasakhir/screens/home.dart'; // Pastikan HomeScreen di-import untuk memanggil _fetchUsers
|
|
|
|
class RegisterScreen extends StatefulWidget {
|
|
const RegisterScreen({Key? key}) : super(key: key);
|
|
|
|
@override
|
|
_RegisterScreenState createState() => _RegisterScreenState();
|
|
}
|
|
|
|
class _RegisterScreenState extends State<RegisterScreen> {
|
|
final TextEditingController _nameController = TextEditingController();
|
|
final TextEditingController _ageController = TextEditingController(); // Controller for age
|
|
|
|
// Function to add new user to Firestore
|
|
void addUser() async {
|
|
if (_nameController.text.isNotEmpty && _ageController.text.isNotEmpty) {
|
|
try {
|
|
// Convert age to an integer
|
|
int age = int.parse(_ageController.text);
|
|
|
|
// Add user data to Firestore
|
|
await FirebaseFirestore.instance.collection('users').add({
|
|
'nama': _nameController.text,
|
|
'umur': age,
|
|
});
|
|
|
|
// Reload the users data to reflect the new user in the dropdown
|
|
Navigator.pop(context);
|
|
// Use Navigator.pop() to close this screen and go back to HomeScreen
|
|
// After returning, the HomeScreen will reload the list of users by calling _fetchUsers()
|
|
|
|
} catch (e) {
|
|
print("Gagal Menambahkan Pengguna: $e");
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
const SnackBar(content: Text('Gagal Menambahkan Pengguna')),
|
|
);
|
|
}
|
|
} else {
|
|
// Show a message if the name or age is empty
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
const SnackBar(content: Text('Masukan Data dengan benar')),
|
|
);
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
appBar: AppBar(
|
|
backgroundColor: const Color(0xFF59A4EB),
|
|
title: const Text('Pendaftaran'),
|
|
),
|
|
body: Padding(
|
|
padding: const EdgeInsets.all(16.0),
|
|
child: Column(
|
|
children: [
|
|
const Text(
|
|
'Masukan Data Pengguna Baru:',
|
|
style: TextStyle(fontSize: 18),
|
|
),
|
|
const SizedBox(height: 16),
|
|
// Input field for the user's name
|
|
TextField(
|
|
controller: _nameController,
|
|
decoration: const InputDecoration(labelText: 'Nama'),
|
|
),
|
|
const SizedBox(height: 16),
|
|
// Input field for the user's age
|
|
TextField(
|
|
controller: _ageController,
|
|
keyboardType: TextInputType.number, // To allow only numeric input
|
|
decoration: const InputDecoration(labelText: 'Umur'),
|
|
),
|
|
const SizedBox(height: 24),
|
|
ElevatedButton(
|
|
onPressed: addUser,
|
|
child: const Text('Tambahkan'),
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: const Color(0xFF59A4EB), // Blue button color
|
|
padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 30),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|