From 91786810c001a365fb475019a5696461f63d2617 Mon Sep 17 00:00:00 2001 From: kleponijo <158453666+kleponijo@users.noreply.github.com> Date: Sat, 9 May 2026 18:40:56 +0700 Subject: [PATCH 1/4] perbaikan authentication --- lib/app_view.dart | 32 +- .../authentication_bloc.dart | 11 +- .../auth/blocs/sign_in_bloc/sign_in_bloc.dart | 2 +- lib/screens/auth/views/sign_in_screen.dart | 223 ++++++---- lib/screens/auth/views/sign_up_screen.dart | 409 ++++++++---------- lib/screens/auth/views/welcome_screen.dart | 125 +++--- .../lib/src/firebase_user_repo.dart | 46 +- .../user_repository/lib/src/models/user.dart | 18 +- 8 files changed, 425 insertions(+), 441 deletions(-) diff --git a/lib/app_view.dart b/lib/app_view.dart index 3fd5d03..0320ddb 100644 --- a/lib/app_view.dart +++ b/lib/app_view.dart @@ -11,25 +11,23 @@ class MyAppView extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( - title: 'Klimatologi', - debugShowCheckedModeBanner: false, - theme: ThemeData( - colorScheme: ColorScheme.light( - background: Colors.grey.shade100, - onBackground: Colors.black, - primary: Colors.blue, - onPrimary: Colors.white + title: 'Klimatologi', + debugShowCheckedModeBanner: false, + theme: ThemeData( + colorScheme: ColorScheme.light( + surface: Colors.grey.shade100, + onSurface: Colors.black, + primary: Colors.blue, + onPrimary: Colors.white), ), - ), - home: BlocBuilder( - builder: ((context, state){ - if(state.status == AuthenticationStatus.authenticated){ - return HomeScreen(); + home: BlocBuilder( + builder: ((context, state) { + if (state.status == AuthenticationStatus.authenticated) { + return HomeScreen(); } else { - return WelcomeScreen(); + return WelcomeScreen(); } }), - ) - ); + )); } -} \ No newline at end of file +} diff --git a/lib/blocs/authentication_bloc/authentication_bloc.dart b/lib/blocs/authentication_bloc/authentication_bloc.dart index 7929c1e..9ff6e4a 100644 --- a/lib/blocs/authentication_bloc/authentication_bloc.dart +++ b/lib/blocs/authentication_bloc/authentication_bloc.dart @@ -7,20 +7,19 @@ import 'package:user_repository/user_repository.dart'; part 'authentication_event.dart'; part 'authentication_state.dart'; -class AuthenticationBloc extends Bloc { +class AuthenticationBloc + extends Bloc { final UserRepository userRepository; late final StreamSubscription _userSubscription; - AuthenticationBloc({ - required this.userRepository - }) : super(const AuthenticationState.unknown()) { + AuthenticationBloc({required this.userRepository}) + : super(const AuthenticationState.unknown()) { _userSubscription = userRepository.user.listen((user) { add(AuthenticationUserChanged(user)); }); - on((event, emit) { - if(event.user != MyUser.empty) { + if (event.user != null && event.user != MyUser.empty) { emit(AuthenticationState.authenticated(event.user!)); } else { emit(AuthenticationState.unauthenticated()); diff --git a/lib/screens/auth/blocs/sign_in_bloc/sign_in_bloc.dart b/lib/screens/auth/blocs/sign_in_bloc/sign_in_bloc.dart index ef52fb0..aa0fbfb 100644 --- a/lib/screens/auth/blocs/sign_in_bloc/sign_in_bloc.dart +++ b/lib/screens/auth/blocs/sign_in_bloc/sign_in_bloc.dart @@ -13,6 +13,7 @@ class SignInBloc extends Bloc { emit(SignInProcess()); try { await _userRepository.signIn(event.email, event.password); + emit(SignInSuccess()); } catch (e) { emit(SignInFailure()); } @@ -25,7 +26,6 @@ class SignInBloc extends Bloc { emit(SignInSuccess()); } catch (e) { emit(SignInFailure()); - emit(SignInInitial()); } }); diff --git a/lib/screens/auth/views/sign_in_screen.dart b/lib/screens/auth/views/sign_in_screen.dart index 84e359a..b4f00f1 100644 --- a/lib/screens/auth/views/sign_in_screen.dart +++ b/lib/screens/auth/views/sign_in_screen.dart @@ -21,47 +21,68 @@ class _SignInScreenState extends State { bool obscurePassword = true; String? _errorMsg; + @override + void dispose() { + emailController.dispose(); + passwordController.dispose(); + super.dispose(); + } + @override Widget build(BuildContext context) { return BlocListener( listener: (context, state) { if (state is SignInProcess) { - setState(() { - signInRequired = true; - }); + setState(() => signInRequired = true); } else { - setState(() { - signInRequired = false; - }); + setState(() => signInRequired = false); + if (state is SignInFailure) { - setState(() { - // PERUBAHAN: Pesan error lebih umum karena Google gagal belum tentu soal password - _errorMsg = 'Sign in failed. Please try again.'; - }); + setState(() => _errorMsg = 'Email atau password salah. Coba lagi.'); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(_errorMsg!), + backgroundColor: Colors.red, + ), + ); + } else if (state is SignInSuccess) { + setState(() => _errorMsg = null); } } }, - child: Form( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Form( key: _formKey, child: Column( children: [ const SizedBox(height: 20), + + // Email field SizedBox( - width: MediaQuery.of(context).size.width * 0.9, - child: MyTextField( - controller: emailController, - hintText: 'Email', - obscureText: false, - keyboardType: TextInputType.emailAddress, - prefixIcon: const Icon(CupertinoIcons.mail_solid), - errorMsg: _errorMsg, - validator: (val) { - if (val!.isEmpty) { - return 'Please fill in this field'; - } - return null; - })), + width: MediaQuery.of(context).size.width * 0.9, + child: MyTextField( + controller: emailController, + hintText: 'Email', + obscureText: false, + keyboardType: TextInputType.emailAddress, + prefixIcon: const Icon(CupertinoIcons.mail_solid), + // FIX: tidak lagi pass errorMsg ke field individual + validator: (val) { + if (val == null || val.isEmpty) { + return 'Mohon isi field ini'; + } + // FIX: tambah validasi format email + if (!RegExp(r'^[\w.-]+@[\w.-]+\.\w{2,}$').hasMatch(val)) { + return 'Format email tidak valid'; + } + return null; + }, + ), + ), const SizedBox(height: 10), + + // Password field SizedBox( width: MediaQuery.of(context).size.width * 0.9, child: MyTextField( @@ -70,10 +91,9 @@ class _SignInScreenState extends State { obscureText: obscurePassword, keyboardType: TextInputType.visiblePassword, prefixIcon: const Icon(CupertinoIcons.lock_fill), - errorMsg: _errorMsg, validator: (val) { - if (val!.isEmpty) { - return 'Please fill in this field'; + if (val == null || val.isEmpty) { + return 'Mohon isi field ini'; } return null; }, @@ -81,85 +101,104 @@ class _SignInScreenState extends State { onPressed: () { setState(() { obscurePassword = !obscurePassword; - if (obscurePassword) { - iconPassword = CupertinoIcons.eye_fill; - } else { - iconPassword = CupertinoIcons.eye_slash_fill; - } + iconPassword = obscurePassword + ? CupertinoIcons.eye_fill + : CupertinoIcons.eye_slash_fill; }); }, icon: Icon(iconPassword), ), ), ), - const SizedBox(height: 20), - !signInRequired - ? SizedBox( - width: MediaQuery.of(context).size.width * 0.5, - child: TextButton( - onPressed: () { - if (_formKey.currentState!.validate()) { - context.read().add(SignInRequired( - emailController.text, - passwordController.text)); - } - }, - style: TextButton.styleFrom( - elevation: 3.0, - backgroundColor: - Theme.of(context).colorScheme.primary, - foregroundColor: Colors.white, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(60))), - child: const Padding( - padding: EdgeInsets.symmetric( - horizontal: 25, vertical: 5), - child: Text( - 'Sign In', - textAlign: TextAlign.center, - style: TextStyle( - color: Colors.white, - fontSize: 16, - fontWeight: FontWeight.w600), - ), - )), - ) - : const CircularProgressIndicator(), - /// ======= Tombol Login Google ======= /// + // FIX: Error message satu baris di bawah kedua field + if (_errorMsg != null) ...[ + const SizedBox(height: 8), + SizedBox( + width: MediaQuery.of(context).size.width * 0.9, + child: Text( + _errorMsg!, + style: const TextStyle(color: Colors.red, fontSize: 13), + ), + ), + ], + const SizedBox(height: 20), - SizedBox( - width: MediaQuery.of(context).size.width * 0.5, - child: TextButton.icon( - onPressed: () { - // == Mengirim event login Google ke Bloc == // - context.read().add(GoogleSignInRequired()); - }, - icon: SizedBox( - height: 20, - width: 20, - child: Image.asset( - 'images/google-icon-logo.png', - fit: BoxFit.contain, + + // FIX: Tombol Sign In dan Google dinonaktifkan saat loading + if (!signInRequired) ...[ + SizedBox( + width: MediaQuery.of(context).size.width * 0.5, + child: TextButton( + onPressed: () { + if (_formKey.currentState!.validate()) { + context.read().add(SignInRequired( + emailController.text, passwordController.text)); + } + }, + style: TextButton.styleFrom( + elevation: 3.0, + backgroundColor: Theme.of(context).colorScheme.primary, + foregroundColor: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(60)), + ), + child: const Padding( + padding: + EdgeInsets.symmetric(horizontal: 25, vertical: 5), + child: Text( + 'Sign In', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.w600), + ), ), ), - label: const Text( - 'Sign In with Google', - style: TextStyle( - color: Colors.black, - fontSize: 16, - fontWeight: FontWeight.w600), - ), - style: TextButton.styleFrom( + ), + const SizedBox(height: 16), + + // Tombol Google — hanya muncul ketika tidak loading + SizedBox( + width: MediaQuery.of(context).size.width * 0.5, + child: TextButton.icon( + onPressed: () { + context.read().add(GoogleSignInRequired()); + }, + icon: SizedBox( + height: 20, + width: 20, + child: Image.asset( + 'images/google-icon-logo.png', + fit: BoxFit.contain, + ), + ), + label: const Text( + 'Sign In with Google', + style: TextStyle( + color: Colors.black, + fontSize: 16, + fontWeight: FontWeight.w600), + ), + style: TextButton.styleFrom( elevation: 3.0, backgroundColor: Colors.white, shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(60), - side: const BorderSide(color: Colors.grey))), + borderRadius: BorderRadius.circular(60), + side: const BorderSide(color: Colors.grey), + ), + ), + ), ), - ), + ] else + const CircularProgressIndicator(), + + const SizedBox(height: 20), ], - )), + ), + ), + ), ); } } diff --git a/lib/screens/auth/views/sign_up_screen.dart b/lib/screens/auth/views/sign_up_screen.dart index 5d50a2f..ef6a919 100644 --- a/lib/screens/auth/views/sign_up_screen.dart +++ b/lib/screens/auth/views/sign_up_screen.dart @@ -1,11 +1,10 @@ -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:user_repository/user_repository.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:user_repository/user_repository.dart'; + import '../../../components/my_text_field.dart'; -import '../blocs/sign_up_bloc/sign_up_bloc.dart' as signUp; -// import '../../../blocs/authentication_bloc/authentication_bloc.dart'; -import '../blocs/sign_in_bloc/sign_in_bloc.dart' as signIn; +import '../blocs/sign_up_bloc/sign_up_bloc.dart'; class SignUpScreen extends StatefulWidget { final VoidCallback? onSignInTap; @@ -24,251 +23,207 @@ class _SignUpScreenState extends State { IconData iconPassword = CupertinoIcons.eye_fill; bool obscurePassword = true; bool signUpRequired = false; + // FIX: Hapus 5 variabel password strength yang tidak dipakai - bool containsUpperCase = false; - bool containsLowerCase = false; - bool containsNumber = false; - bool containsSpecialChar = false; - bool contains8Length = false; + @override + void dispose() { + nameController.dispose(); + emailController.dispose(); + passwordController.dispose(); + confirmPasswordController.dispose(); + super.dispose(); + } @override Widget build(BuildContext context) { - return BlocListener( + return BlocListener( listener: (context, state) { - if (state is signUp.SignUpProcess) { - setState(() { - signUpRequired = true; - }); - } else if (state is signUp.SignUpFailure) { - setState(() { - signUpRequired = false; // Matikan loading! - }); - // Tampilkan pesan error lewat Snackbar biar user tahu kenapa gagal + if (state is SignUpProcess) { + setState(() => signUpRequired = true); + } else if (state is SignUpFailure) { + setState(() => signUpRequired = false); ScaffoldMessenger.of(context).showSnackBar( SnackBar( - content: Text(state.message ?? 'An error ocurred'), - backgroundColor: Colors.red), + content: Text(state.message ?? 'Terjadi kesalahan'), + backgroundColor: Colors.red, + ), ); - } else if (state is signUp.SignUpSuccess) { - setState(() { - signUpRequired = false; - }); + } else if (state is SignUpSuccess) { + setState(() => signUpRequired = false); } }, + // FIX: Hapus Scaffold — WelcomeScreen sudah punya Scaffold child: Form( key: _formKey, - child: Scaffold( - backgroundColor: Colors.white, - body: Center( - child: SingleChildScrollView( - child: Column( - children: [ - const SizedBox(height: 30), - Container( - width: MediaQuery.of(context).size.width * 0.92, - padding: const EdgeInsets.symmetric( - horizontal: 20, vertical: 22), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(12), - boxShadow: [ - BoxShadow( - color: Colors.black.withOpacity(0.04), - blurRadius: 10, - offset: const Offset(0, 4), - ) - ], - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const SizedBox(height: 6), - const Center( - child: Text( - 'Buat Akun', - style: TextStyle( - fontSize: 22, fontWeight: FontWeight.w700), - ), - ), - const SizedBox(height: 6), - const Center( - child: Text( - 'Daftar untuk mulai monitoring', - style: - TextStyle(fontSize: 13, color: Colors.black54), - ), - ), - const SizedBox(height: 14), + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Center( + child: Text( + 'Buat Akun', + style: TextStyle(fontSize: 22, fontWeight: FontWeight.w700), + ), + ), + const SizedBox(height: 6), + const Center( + child: Text( + 'Daftar untuk mulai monitoring', + style: TextStyle(fontSize: 13, color: Colors.black54), + ), + ), + const SizedBox(height: 20), - // Name - SizedBox( - width: MediaQuery.of(context).size.width * 0.9, - child: MyTextField( - controller: nameController, - hintText: 'Masukkan nama lengkap', - obscureText: false, - keyboardType: TextInputType.name, - prefixIcon: const Icon(CupertinoIcons.person_fill), - validator: (val) { - if (val == null || val.isEmpty) { - return 'Please fill in this field'; - } else if (val.length > 50) { - return 'Name too long'; - } - return null; - }, - ), - ), - const SizedBox(height: 10), + // Nama + MyTextField( + controller: nameController, + hintText: 'Masukkan nama lengkap', + obscureText: false, + keyboardType: TextInputType.name, + prefixIcon: const Icon(CupertinoIcons.person_fill), + validator: (val) { + if (val == null || val.isEmpty) { + return 'Mohon isi field ini'; + } + if (val.length > 50) return 'Nama terlalu panjang'; + return null; + }, + ), + const SizedBox(height: 10), - // Email - SizedBox( - width: MediaQuery.of(context).size.width * 0.9, - child: MyTextField( - controller: emailController, - hintText: 'nama@email.com', - obscureText: false, - keyboardType: TextInputType.emailAddress, - prefixIcon: const Icon(CupertinoIcons.mail_solid), - validator: (val) { - if (val == null || val.isEmpty) { - return 'Please fill in this field'; - } - return null; - }, - ), - ), - const SizedBox(height: 10), + // Email + MyTextField( + controller: emailController, + hintText: 'nama@email.com', + obscureText: false, + keyboardType: TextInputType.emailAddress, + prefixIcon: const Icon(CupertinoIcons.mail_solid), + validator: (val) { + if (val == null || val.isEmpty) { + return 'Mohon isi field ini'; + } + // FIX: tambah validasi format email + if (!RegExp(r'^[\w.-]+@[\w.-]+\.\w{2,}$').hasMatch(val)) { + return 'Format email tidak valid'; + } + return null; + }, + ), + const SizedBox(height: 10), - // Password - SizedBox( - width: MediaQuery.of(context).size.width * 0.9, - child: MyTextField( - controller: passwordController, - hintText: 'Minimal 6 karakter', - obscureText: obscurePassword, - keyboardType: TextInputType.visiblePassword, - prefixIcon: const Icon(CupertinoIcons.lock_fill), - suffixIcon: IconButton( - onPressed: () { - setState(() { - obscurePassword = !obscurePassword; - iconPassword = obscurePassword - ? CupertinoIcons.eye_fill - : CupertinoIcons.eye_slash_fill; - }); - }, - icon: Icon(iconPassword), + // Password + MyTextField( + controller: passwordController, + hintText: 'Minimal 6 karakter', + obscureText: obscurePassword, + keyboardType: TextInputType.visiblePassword, + prefixIcon: const Icon(CupertinoIcons.lock_fill), + suffixIcon: IconButton( + onPressed: () { + setState(() { + obscurePassword = !obscurePassword; + iconPassword = obscurePassword + ? CupertinoIcons.eye_fill + : CupertinoIcons.eye_slash_fill; + }); + }, + icon: Icon(iconPassword), + ), + validator: (val) { + if (val == null || val.isEmpty) { + return 'Mohon isi field ini'; + } + // FIX: tambah validasi panjang minimum + if (val.length < 6) { + return 'Password minimal 6 karakter'; + } + return null; + }, + ), + const SizedBox(height: 10), + + // Confirm Password + MyTextField( + controller: confirmPasswordController, + hintText: 'Ulangi password', + obscureText: obscurePassword, + keyboardType: TextInputType.visiblePassword, + prefixIcon: const Icon(CupertinoIcons.lock_fill), + validator: (val) { + if (val == null || val.isEmpty) { + return 'Mohon isi field ini'; + } + if (val != passwordController.text) { + return 'Password tidak cocok'; + } + return null; + }, + ), + + const SizedBox(height: 24), + + // Tombol Sign Up + Center( + child: !signUpRequired + ? SizedBox( + width: MediaQuery.of(context).size.width * 0.5, + child: ElevatedButton( + onPressed: () { + if (_formKey.currentState!.validate()) { + // FIX: buat MyUser langsung, jangan mutasi MyUser.empty + final myUser = MyUser( + userId: '', + email: emailController.text.trim(), + name: nameController.text.trim(), + hasActiveCart: false, + ); + + // FIX: add() dipanggil di luar setState + context.read().add( + SignUpRequired( + myUser, passwordController.text), + ); + } + }, + style: ElevatedButton.styleFrom( + backgroundColor: + Theme.of(context).colorScheme.primary, + foregroundColor: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(60), + ), + ), + child: const Padding( + padding: EdgeInsets.symmetric( + horizontal: 25, vertical: 5), + child: Text( + 'Sign Up', + style: TextStyle( + fontSize: 16, fontWeight: FontWeight.w600), ), - validator: (val) { - if (val == null || val.isEmpty) { - return 'Please fill in this field'; - } - return null; - }, ), ), - const SizedBox(height: 10), + ) + : const CircularProgressIndicator(), + ), - // Confirm Password - SizedBox( - width: MediaQuery.of(context).size.width * 0.9, - child: MyTextField( - controller: confirmPasswordController, - hintText: 'Ulangi password', - obscureText: obscurePassword, - keyboardType: TextInputType.visiblePassword, - prefixIcon: const Icon(CupertinoIcons.lock_fill), - validator: (val) { - if (val == null || val.isEmpty) { - return 'Please fill in this field'; - } else if (val != passwordController.text) { - return 'Password tidak cocok'; - } - return null; - }, - ), - ), - - const SizedBox(height: 18), - - /// == Sign Up == /// - // Button - !signUpRequired - ? Center( - child: SizedBox( - width: - MediaQuery.of(context).size.width * 0.5, - child: ElevatedButton( - onPressed: () { - if (_formKey.currentState!.validate()) { - MyUser myUser = MyUser.empty; - myUser.email = emailController.text; - myUser.name = nameController.text; - - setState(() { - context.read().add( - signUp.SignUpRequired( - myUser, - passwordController.text, - ), - ); - }); - } - }, - style: TextButton.styleFrom( - backgroundColor: - Theme.of(context).colorScheme.primary, - foregroundColor: Colors.white, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(60), - ), - ), - child: Padding( - padding: EdgeInsets.symmetric( - horizontal: 25, vertical: 5), - child: const Text( - 'Sign Up', - style: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600), - ), - ), - ), - ), - ) - : const CircularProgressIndicator(), - - const SizedBox(height: 12), - Center( - child: Text('Atau'), - ), - - const SizedBox(height: 12), - Center( - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Text('Sudah punya akun? '), - TextButton( - onPressed: () { - widget.onSignInTap?.call(); - }, - child: const Text( - 'Login di sini', - style: TextStyle(fontWeight: FontWeight.bold), - ), - ) - ], - ), - ), - ], + const SizedBox(height: 16), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Text('Sudah punya akun? '), + TextButton( + onPressed: widget.onSignInTap, + child: const Text( + 'Login di sini', + style: TextStyle(fontWeight: FontWeight.bold), ), ), - const SizedBox(height: 30), ], ), - ), + const SizedBox(height: 16), + ], ), ), ), diff --git a/lib/screens/auth/views/welcome_screen.dart b/lib/screens/auth/views/welcome_screen.dart index 2a5444c..5c11126 100644 --- a/lib/screens/auth/views/welcome_screen.dart +++ b/lib/screens/auth/views/welcome_screen.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import '../../../blocs/authentication_bloc/authentication_bloc.dart'; +import 'package:user_repository/user_repository.dart'; + import '../blocs/sign_in_bloc/sign_in_bloc.dart'; import '../blocs/sign_up_bloc/sign_up_bloc.dart'; import 'sign_in_screen.dart'; @@ -19,84 +20,66 @@ class _WelcomeScreenState extends State @override void initState() { - tabController = TabController(initialIndex: 0, length: 2, vsync: this); super.initState(); + tabController = TabController(initialIndex: 0, length: 2, vsync: this); + } + + @override + void dispose() { + tabController.dispose(); // FIX: dispose controller agar tidak memory leak + super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, - body: SingleChildScrollView( - child: SizedBox( - height: MediaQuery.of(context).size.height, - child: Stack( - children: [ - Align( - alignment: Alignment.center, - child: SizedBox( - height: MediaQuery.of(context).size.height / 1.8, - child: Column( - children: [ - Padding( - padding: const EdgeInsets.symmetric(horizontal: 50.0), - child: TabBar( - controller: tabController, - unselectedLabelColor: Theme.of(context) - .colorScheme - .onBackground - .withOpacity(0.5), - labelColor: - Theme.of(context).colorScheme.onBackground, - tabs: const [ - Padding( - padding: EdgeInsets.all(12.0), - child: Text( - 'Sign In', - style: TextStyle( - fontSize: 18, - ), - ), - ), - Padding( - padding: EdgeInsets.all(12.0), - child: Text( - 'Sign Up', - style: TextStyle( - fontSize: 18, - ), - ), - ), - ], - ), - ), - Expanded( - child: TabBarView( - controller: tabController, - children: [ - BlocProvider( - create: (context) => SignInBloc(context - .read() - .userRepository), - child: const SignInScreen(), - ), - BlocProvider( - create: (context) => SignUpBloc(context - .read() - .userRepository), - child: SignUpScreen(onSignInTap: () { - tabController.animateTo( - 0); // Ini yang bikin dia pindah ke tab Login - }), - ), - ], - )) - ], + body: SafeArea( + child: Column( + children: [ + const SizedBox(height: 24), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 50.0), + child: TabBar( + controller: tabController, + unselectedLabelColor: + Theme.of(context).colorScheme.onSurface.withOpacity(0.5), + labelColor: Theme.of(context).colorScheme.onSurface, + tabs: const [ + Padding( + padding: EdgeInsets.all(12.0), + child: Text('Sign In', style: TextStyle(fontSize: 18)), ), - ), - ) - ], - ), + Padding( + padding: EdgeInsets.all(12.0), + child: Text('Sign Up', style: TextStyle(fontSize: 18)), + ), + ], + ), + ), + // FIX: Expanded supaya TabBarView mengisi sisa tinggi layar + // dengan ini scroll di dalam tab bisa berjalan normal + Expanded( + child: TabBarView( + controller: tabController, + children: [ + BlocProvider( + create: (context) => + // FIX: akses UserRepository langsung, bukan via AuthBloc + SignInBloc(context.read()), + child: const SignInScreen(), + ), + BlocProvider( + create: (context) => + SignUpBloc(context.read()), + child: SignUpScreen( + onSignInTap: () => tabController.animateTo(0), + ), + ), + ], + ), + ), + ], ), ), ); diff --git a/packages/user_repository/lib/src/firebase_user_repo.dart b/packages/user_repository/lib/src/firebase_user_repo.dart index f816dc5..a9d5126 100644 --- a/packages/user_repository/lib/src/firebase_user_repo.dart +++ b/packages/user_repository/lib/src/firebase_user_repo.dart @@ -10,11 +10,9 @@ class FirebaseUserRepo implements UserRepository { final FirebaseAuth _firebaseAuth; final userCollection = FirebaseFirestore.instance.collection('users'); - FirebaseUserRepo({ - FirebaseAuth? firebaseAuth, - }) : _firebaseAuth = firebaseAuth ?? FirebaseAuth.instance; + FirebaseUserRepo({FirebaseAuth? firebaseAuth}) + : _firebaseAuth = firebaseAuth ?? FirebaseAuth.instance; - /// == Melakukan Implement User == /// @override Stream get user { return _firebaseAuth.authStateChanges().flatMap((firebaseUser) async* { @@ -27,15 +25,8 @@ class FirebaseUserRepo implements UserRepository { yield MyUser.fromEntity( MyUserEntity.fromDocument(userData.data()!)); } else { - // User baru yang belum ada data di Firestore, tunggu sebentar - await Future.delayed(const Duration(milliseconds: 500)); - final retryData = await userCollection.doc(firebaseUser.uid).get(); - if (retryData.exists && retryData.data() != null) { - yield MyUser.fromEntity( - MyUserEntity.fromDocument(retryData.data()!)); - } else { - yield MyUser.empty; - } + // Data Firestore belum ada (seharusnya tidak terjadi dengan flow yang sudah diperbaiki) + yield MyUser.empty; } } catch (e) { log('Error fetching user data: $e'); @@ -45,7 +36,6 @@ class FirebaseUserRepo implements UserRepository { }); } - /// == Melakukan Implement Sign in == /// @override Future signIn(String email, String password) async { try { @@ -57,7 +47,6 @@ class FirebaseUserRepo implements UserRepository { } } - /// == Melakukan Implement Sign Up == /// @override Future signUp(MyUser myUser, String password) async { try { @@ -71,7 +60,6 @@ class FirebaseUserRepo implements UserRepository { } } - /// == Melakukan Implement Log Out == /// @override Future logOut() async { final GoogleSignIn googleSignIn = GoogleSignIn(); @@ -85,27 +73,26 @@ class FirebaseUserRepo implements UserRepository { await userCollection .doc(myUser.userId) .set(myUser.toEntity().toDocument()); - // Tunggu sebentar agar data tersimpan dengan baik sebelum stream update - await Future.delayed(const Duration(milliseconds: 500)); } catch (e) { log(e.toString()); rethrow; } } - /// == Sign in with Google == /// @override Future signInWithGoogle() async { try { + UserCredential userCredential; + if (kIsWeb) { final googleProvider = GoogleAuthProvider(); - await _firebaseAuth.signInWithPopup(googleProvider); + userCredential = await _firebaseAuth.signInWithPopup(googleProvider); } else { final GoogleSignIn googleSignIn = GoogleSignIn(); final googleUser = await googleSignIn.signIn(); if (googleUser == null) { - throw Exception("cancelled"); + throw Exception('cancelled'); } final GoogleSignInAuthentication googleAuth = @@ -115,7 +102,22 @@ class FirebaseUserRepo implements UserRepository { accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); - await _firebaseAuth.signInWithCredential(credential); + userCredential = await _firebaseAuth.signInWithCredential(credential); + } + + // FIX: Cek apakah user sudah punya data Firestore + // Jika belum (user baru), buat dokumen sekarang juga + final firebaseUser = userCredential.user!; + final doc = await userCollection.doc(firebaseUser.uid).get(); + + if (!doc.exists) { + final newUser = MyUser( + userId: firebaseUser.uid, + email: firebaseUser.email ?? '', + name: firebaseUser.displayName ?? '', + hasActiveCart: false, + ); + await setUserData(newUser); } } catch (e) { log('Google sign-in error: $e'); diff --git a/packages/user_repository/lib/src/models/user.dart b/packages/user_repository/lib/src/models/user.dart index 745028f..e867c7a 100644 --- a/packages/user_repository/lib/src/models/user.dart +++ b/packages/user_repository/lib/src/models/user.dart @@ -1,4 +1,3 @@ - import '../entities/entities.dart'; class MyUser { @@ -7,12 +6,11 @@ class MyUser { String name; bool hasActiveCart; - MyUser ({ + MyUser({ required this.userId, required this.email, required this.name, required this.hasActiveCart, - }); static final empty = MyUser( @@ -40,9 +38,19 @@ class MyUser { ); } + @override + bool operator ==(Object other) => + identical(this, other) || + other is MyUser && + runtimeType == other.runtimeType && + userId == other.userId && + email == other.email; + + @override + int get hashCode => Object.hash(userId, email); + @override String toString() { return 'MyUser: $userId, email: $email, name: $name, hasActiveCart: $hasActiveCart}'; } - -} \ No newline at end of file +} From ca49ffc774ff8fa2fdc6168a97f69a2d2b745692 Mon Sep 17 00:00:00 2001 From: kleponijo <158453666+kleponijo@users.noreply.github.com> Date: Sat, 9 May 2026 20:22:15 +0700 Subject: [PATCH 2/4] Update evaporasi.dart --- packages/monitoring_repository/lib/src/models/evaporasi.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/monitoring_repository/lib/src/models/evaporasi.dart b/packages/monitoring_repository/lib/src/models/evaporasi.dart index caec82e..168e2a5 100644 --- a/packages/monitoring_repository/lib/src/models/evaporasi.dart +++ b/packages/monitoring_repository/lib/src/models/evaporasi.dart @@ -30,14 +30,14 @@ class Evaporasi implements HasTimestamp { // History path : suhu, tinggi, evaporasi, waktu // Realtime path : suhu_air, tinggi_air, evaporasi, waktu, status final suhu = (json['suhu'] ?? json['suhu_air'] ?? 0).toDouble(); - final tinggi = (json['tinggi'] ?? json['tinggi_air'] ?? 0).toDouble(); + final tinggi = (json['tinggi'] ?? json['tinggi_air_cm'] ?? 0).toDouble(); // ✅ Prioritas: timestamp (Unix, kalau firmware sudah diupdate) // → fallback ke waktu ("HH:MM:SS") final rawTime = json['timestamp'] ?? json['waktu']; return Evaporasi( - evaporasi: (json['evaporasi'] ?? 0).toDouble(), + evaporasi: (json['evaporasi_mm'] ?? 0).toDouble(), suhu: suhu, tinggiAir: tinggi, status: json['status'] ?? '', From 5913bd036611836fad0442eecb53d386090f5f57 Mon Sep 17 00:00:00 2001 From: kleponijo <158453666+kleponijo@users.noreply.github.com> Date: Sat, 9 May 2026 20:31:06 +0700 Subject: [PATCH 3/4] Update pubspec.lock --- pubspec.lock | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/pubspec.lock b/pubspec.lock index 4867820..ae5f51c 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -695,6 +695,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.27.7" + simple_gesture_detector: + dependency: transitive + description: + name: simple_gesture_detector + sha256: ba2cd5af24ff20a0b8d609cec3f40e5b0744d2a71804a2616ae086b9c19d19a3 + url: "https://pub.dev" + source: hosted + version: "0.2.1" sky_engine: dependency: transitive description: flutter @@ -740,6 +748,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.1" + table_calendar: + dependency: "direct main" + description: + name: table_calendar + sha256: "0c0c6219878b363a2d5f40c7afb159d845f253d061dc3c822aa0d5fe0f721982" + url: "https://pub.dev" + source: hosted + version: "3.2.0" term_glyph: dependency: transitive description: From f3ab71616e4793b6f7d3843baee015174aa5d6ce Mon Sep 17 00:00:00 2001 From: kleponijo <158453666+kleponijo@users.noreply.github.com> Date: Sat, 9 May 2026 20:52:03 +0700 Subject: [PATCH 4/4] oke --- lib/screens/home/views/home_screen.dart | 15 -- .../evaporasi/blocs/evaporasi_bloc.dart | 6 +- .../views/widgets/evaporasi_chart_widget.dart | 170 ++++++++++++++++++ .../views/widgets/evaporasi_date_picker.dart | 168 ++++++++--------- .../widgets/evaporasi_date_search_bar.dart | 18 -- .../lib/src/models/evaporasi.dart | 47 ++--- test/widget_test.dart | 36 ++-- 7 files changed, 299 insertions(+), 161 deletions(-) create mode 100644 lib/screens/monitoring/evaporasi/views/widgets/evaporasi_chart_widget.dart diff --git a/lib/screens/home/views/home_screen.dart b/lib/screens/home/views/home_screen.dart index 1a831fb..a495092 100644 --- a/lib/screens/home/views/home_screen.dart +++ b/lib/screens/home/views/home_screen.dart @@ -2,7 +2,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:monitoring_repository/monitoring_repository.dart'; import '../../../blocs/authentication_bloc/authentication_bloc.dart'; -<<<<<<< HEAD import '../../../blocs/notification_bloc/notification_bloc.dart'; import '../../monitoring/wind_speed/blocs/wind_speed_bloc.dart'; import '../../monitoring/evaporasi/blocs/evaporasi_bloc.dart'; @@ -10,8 +9,6 @@ import '../../monitoring/atmospheric_conditions/blocs/atmospheric_conditions_blo import '../widgets/notification_panel.dart'; import '../widgets/sensor_grid.dart'; import '../widgets/dashboard_charts.dart'; -======= ->>>>>>> parent of 6f38d3b (update evaporsi) import 'main_drawer.dart'; class HomeScreen extends StatefulWidget { @@ -100,7 +97,6 @@ class _HomeScreenState extends State height: 90, fit: BoxFit.contain, ), -<<<<<<< HEAD actions: [ // Icon lonceng dengan badge BlocBuilder( @@ -178,17 +174,6 @@ class _HomeScreenState extends State ), ), ], -======= - const SizedBox(width: 10), - ], - ), - actions: [ - IconButton( - icon: const Icon(Icons.notifications_none, color: Colors.black), - onPressed: () { - // Aksi notifikasi - }, ->>>>>>> parent of 6f38d3b (update evaporsi) ), ), ), diff --git a/lib/screens/monitoring/evaporasi/blocs/evaporasi_bloc.dart b/lib/screens/monitoring/evaporasi/blocs/evaporasi_bloc.dart index d1093b7..0cee0c6 100644 --- a/lib/screens/monitoring/evaporasi/blocs/evaporasi_bloc.dart +++ b/lib/screens/monitoring/evaporasi/blocs/evaporasi_bloc.dart @@ -79,11 +79,16 @@ class EvaporasiBloc extends Bloc { ); final lastValue = history.isNotEmpty ? history.last.evaporasi : 0.0; + final lastWaterLevel = history.isNotEmpty ? history.last.tinggiAir : 0.0; + final lastTemperature = history.isNotEmpty ? history.last.suhu : 0.0; final (status, rain) = _computeWeatherStatus(lastValue); _emitEvaporasiAlert(status, rain, lastValue); emit(state.copyWith( history: history, + currentValue: lastValue, + waterLevel: lastWaterLevel, + temperature: lastTemperature, dailyValues: dailyGraph, dailyTemperatures: dailyTempGraph, weeklyValues: weeklyGraph, @@ -299,4 +304,3 @@ class _EvaporasiRealtimeUpdated extends EvaporasiEvent { @override List get props => [data]; } - diff --git a/lib/screens/monitoring/evaporasi/views/widgets/evaporasi_chart_widget.dart b/lib/screens/monitoring/evaporasi/views/widgets/evaporasi_chart_widget.dart new file mode 100644 index 0000000..1595749 --- /dev/null +++ b/lib/screens/monitoring/evaporasi/views/widgets/evaporasi_chart_widget.dart @@ -0,0 +1,170 @@ +import 'package:fl_chart/fl_chart.dart'; +import 'package:flutter/material.dart'; + +class EvaporasiChartWidget extends StatelessWidget { + final List dailyValues; + final List dailyTemperatures; + final String period; + final List chartLabels; + + const EvaporasiChartWidget({ + super.key, + required this.dailyValues, + required this.dailyTemperatures, + required this.period, + required this.chartLabels, + }); + + double _safeValue(double value) { + if (value.isNaN || value.isInfinite) return 0.0; + return value < 0 ? 0.0 : value; + } + + double _maxY() { + final values = [ + ...dailyValues.map(_safeValue), + ...dailyTemperatures.map(_safeValue), + ]; + if (values.isEmpty) return 10; + final maxValue = values.reduce((a, b) => a > b ? a : b); + return (maxValue * 1.4).clamp(10.0, 100.0); + } + + List _lineSpots(List series) { + return series.asMap().entries.map((entry) { + return FlSpot(entry.key.toDouble(), _safeValue(entry.value)); + }).toList(); + } + + String _getBottomLabel(int index) { + if (chartLabels.isEmpty || index < 0 || index >= chartLabels.length) { + return index.toString(); + } + return chartLabels[index]; + } + + @override + Widget build(BuildContext context) { + final values = _lineSpots(dailyValues); + final temperatures = _lineSpots(dailyTemperatures); + + if (values.isEmpty && temperatures.isEmpty) { + return Container( + height: 240, + alignment: Alignment.center, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(25), + boxShadow: [ + BoxShadow( + color: Colors.black.withAlpha(13), + blurRadius: 10, + offset: const Offset(0, 5), + ) + ], + ), + child: const Text('Tidak ada data chart'), + ); + } + + return Container( + height: 300, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(25), + boxShadow: [ + BoxShadow( + color: Colors.black.withAlpha(13), + blurRadius: 10, + offset: const Offset(0, 5), + ) + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(25), + child: Padding( + padding: const EdgeInsets.all(12), + child: LineChart( + LineChartData( + minY: 0, + maxY: _maxY(), + gridData: FlGridData(show: false), + borderData: FlBorderData(show: false), + titlesData: FlTitlesData( + bottomTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + reservedSize: 32, + interval: 1, + getTitlesWidget: (value, meta) { + final index = value.toInt(); + return Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + _getBottomLabel(index), + style: + const TextStyle(color: Colors.grey, fontSize: 10), + ), + ); + }, + ), + ), + leftTitles: const AxisTitles( + sideTitles: SideTitles(showTitles: false), + ), + topTitles: const AxisTitles( + sideTitles: SideTitles(showTitles: false), + ), + rightTitles: const AxisTitles( + sideTitles: SideTitles(showTitles: false), + ), + ), + lineTouchData: LineTouchData( + handleBuiltInTouches: true, + touchTooltipData: LineTouchTooltipData( + getTooltipItems: (spots) { + return spots.map((spot) { + return LineTooltipItem( + spot.y.toStringAsFixed(1), + const TextStyle(color: Colors.white, fontSize: 12), + ); + }).toList(); + }, + ), + ), + lineBarsData: [ + if (values.isNotEmpty) + LineChartBarData( + spots: values, + isCurved: true, + color: Colors.blue.shade700, + barWidth: 3, + dotData: FlDotData(show: false), + belowBarData: BarAreaData( + show: true, + gradient: LinearGradient( + colors: [ + Colors.blue.withAlpha(64), + Colors.blue.withAlpha(13), + ], + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + ), + ), + ), + if (temperatures.isNotEmpty) + LineChartBarData( + spots: temperatures, + isCurved: true, + color: Colors.orange.shade700, + barWidth: 3, + dotData: FlDotData(show: false), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/screens/monitoring/evaporasi/views/widgets/evaporasi_date_picker.dart b/lib/screens/monitoring/evaporasi/views/widgets/evaporasi_date_picker.dart index 1f08115..62274bc 100644 --- a/lib/screens/monitoring/evaporasi/views/widgets/evaporasi_date_picker.dart +++ b/lib/screens/monitoring/evaporasi/views/widgets/evaporasi_date_picker.dart @@ -83,93 +83,95 @@ class _EvaporasiDatePickerState extends State { ), // Calendar Expanded( - child: TableCalendar( - firstDay: DateTime.utc(2020, 1, 1), - lastDay: DateTime.now(), - focusedDay: _focusedDay, - calendarFormat: _calendarFormat, - selectedDayPredicate: (day) { - return isSameDay(_selectedDay, day); - }, - onDaySelected: (selectedDay, focusedDay) { - setState(() { - _selectedDay = selectedDay; - _focusedDay = focusedDay; - }); - }, - onFormatChanged: (format) { - if (_calendarFormat != format) { + child: SingleChildScrollView( + child: TableCalendar( + firstDay: DateTime.utc(2020, 1, 1), + lastDay: DateTime.now(), + focusedDay: _focusedDay, + calendarFormat: _calendarFormat, + selectedDayPredicate: (day) { + return isSameDay(_selectedDay, day); + }, + onDaySelected: (selectedDay, focusedDay) { setState(() { - _calendarFormat = format; + _selectedDay = selectedDay; + _focusedDay = focusedDay; }); - } - }, - onPageChanged: (focusedDay) { - _focusedDay = focusedDay; - }, - calendarStyle: CalendarStyle( - // Default - defaultDecoration: BoxDecoration( - color: Colors.transparent, - shape: BoxShape.circle, + }, + onFormatChanged: (format) { + if (_calendarFormat != format) { + setState(() { + _calendarFormat = format; + }); + } + }, + onPageChanged: (focusedDay) { + _focusedDay = focusedDay; + }, + calendarStyle: CalendarStyle( + // Default + defaultDecoration: BoxDecoration( + color: Colors.transparent, + shape: BoxShape.circle, + ), + // Today + todayDecoration: BoxDecoration( + color: Colors.blue.shade100, + shape: BoxShape.circle, + ), + todayTextStyle: TextStyle( + color: Colors.blue.shade700, + fontWeight: FontWeight.bold, + ), + // Selected + selectedDecoration: BoxDecoration( + color: Colors.blue, + shape: BoxShape.circle, + ), + selectedTextStyle: const TextStyle( + color: Colors.white, + fontWeight: FontWeight.bold, + ), + // Outside days + outsideDaysVisible: false, + weekendTextStyle: TextStyle(color: Colors.grey.shade600), ), - // Today - todayDecoration: BoxDecoration( - color: Colors.blue.shade100, - shape: BoxShape.circle, + headerStyle: HeaderStyle( + formatButtonVisible: true, + titleCentered: true, + formatButtonShowsNext: false, + formatButtonDecoration: BoxDecoration( + border: Border.all(color: Colors.blue), + borderRadius: BorderRadius.circular(12), + ), + formatButtonTextStyle: const TextStyle( + color: Colors.blue, + ), + titleTextStyle: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: Colors.grey.shade700, + ), + leftChevronIcon: Icon( + Icons.chevron_left, + color: Colors.grey.shade600, + ), + rightChevronIcon: Icon( + Icons.chevron_right, + color: Colors.grey.shade600, + ), ), - todayTextStyle: TextStyle( - color: Colors.blue.shade700, - fontWeight: FontWeight.bold, - ), - // Selected - selectedDecoration: BoxDecoration( - color: Colors.blue, - shape: BoxShape.circle, - ), - selectedTextStyle: const TextStyle( - color: Colors.white, - fontWeight: FontWeight.bold, - ), - // Outside days - outsideDaysVisible: false, - weekendTextStyle: TextStyle(color: Colors.grey.shade600), - ), - headerStyle: HeaderStyle( - formatButtonVisible: true, - titleCentered: true, - formatButtonShowsNext: false, - formatButtonDecoration: BoxDecoration( - border: Border.all(color: Colors.blue), - borderRadius: BorderRadius.circular(12), - ), - formatButtonTextStyle: const TextStyle( - color: Colors.blue, - ), - titleTextStyle: TextStyle( - fontSize: 16, - fontWeight: FontWeight.bold, - color: Colors.grey.shade700, - ), - leftChevronIcon: Icon( - Icons.chevron_left, - color: Colors.grey.shade600, - ), - rightChevronIcon: Icon( - Icons.chevron_right, - color: Colors.grey.shade600, - ), - ), - daysOfWeekStyle: DaysOfWeekStyle( - weekdayStyle: TextStyle( - color: Colors.grey.shade500, - fontWeight: FontWeight.w500, - fontSize: 12, - ), - weekendStyle: TextStyle( - color: Colors.grey.shade500, - fontWeight: FontWeight.w500, - fontSize: 12, + daysOfWeekStyle: DaysOfWeekStyle( + weekdayStyle: TextStyle( + color: Colors.grey.shade500, + fontWeight: FontWeight.w500, + fontSize: 12, + ), + weekendStyle: TextStyle( + color: Colors.grey.shade500, + fontWeight: FontWeight.w500, + fontSize: 12, + ), ), ), ), diff --git a/lib/screens/monitoring/evaporasi/views/widgets/evaporasi_date_search_bar.dart b/lib/screens/monitoring/evaporasi/views/widgets/evaporasi_date_search_bar.dart index bf29d28..ea17f0e 100644 --- a/lib/screens/monitoring/evaporasi/views/widgets/evaporasi_date_search_bar.dart +++ b/lib/screens/monitoring/evaporasi/views/widgets/evaporasi_date_search_bar.dart @@ -1,7 +1,4 @@ import 'package:flutter/material.dart'; -import 'package:intl/intl.dart'; - -import 'package:monitoring_repository/monitoring_repository.dart'; class EvaporasiDateSearchBar extends StatefulWidget { final String initialQuery; @@ -13,14 +10,12 @@ class EvaporasiDateSearchBar extends StatefulWidget { required this.onQueryChanged, }); - @override State createState() => _EvaporasiDateSearchBarState(); } class _EvaporasiDateSearchBarState extends State { late final TextEditingController _controller; - DateTime? _selected; @override void initState() { @@ -34,21 +29,9 @@ class _EvaporasiDateSearchBarState extends State { super.dispose(); } - bool _matches(Evaporasi item, String query) { - if (query.trim().isEmpty) return true; - - final date = item.timestamp; - final ddMMyyyy = DateFormat('dd/MM/yyyy', 'id_ID').format(date); - final ddMMMYYYY = DateFormat('dd MMM yyyy', 'id_ID').format(date); - - final q = query.trim().toLowerCase(); - return ddMMyyyy.toLowerCase().contains(q) || ddMMMYYYY.toLowerCase().contains(q); - } - @override Widget build(BuildContext context) { return TextField( - controller: _controller, decoration: InputDecoration( hintText: 'Cari tanggal (dd/MM/yyyy)', @@ -69,4 +52,3 @@ class _EvaporasiDateSearchBarState extends State { ); } } - diff --git a/packages/monitoring_repository/lib/src/models/evaporasi.dart b/packages/monitoring_repository/lib/src/models/evaporasi.dart index 912d044..ecf5a3a 100644 --- a/packages/monitoring_repository/lib/src/models/evaporasi.dart +++ b/packages/monitoring_repository/lib/src/models/evaporasi.dart @@ -19,17 +19,21 @@ class Evaporasi { ); factory Evaporasi.fromJson(Map json) { - // ✅ Handle perbedaan field name antara history dan realtime: - // History path : suhu, tinggi, evaporasi, waktu - // Realtime path : suhu_air, tinggi_air, evaporasi, waktu, status - final suhu = (json['suhu'] ?? json['suhu_air'] ?? 0).toDouble(); - final tinggi = (json['tinggi'] ?? json['tinggi_air_cm'] ?? 0).toDouble(); + double toDoubleSafe(dynamic v) { + if (v is num) return v.toDouble(); + if (v is String) return double.tryParse(v) ?? 0; + return 0; + } - // ✅ Prioritas waktu sesuai firmware ESP32: - // 1) timestamp (Unix atau ISO string, kalau pernah dikirim) - // 2) datetime ("YYYY-MM-DD HH:MM:SS") - // 3) waktu ("HH:MM:SS") fallback (pakai tanggal hari ini) + final evaporasiVal = toDoubleSafe( + json['evaporasi_mm'] ?? json['evaporasi'], + ); + final suhuVal = toDoubleSafe(json['suhu'] ?? json['suhu_air']); + final tinggiVal = toDoubleSafe(json['tinggi_air_cm'] ?? json['tinggi_air']); + + DateTime timestamp = DateTime.now(); final rawTimestamp = json['timestamp']; + if (rawTimestamp != null) { if (rawTimestamp is int) { timestamp = DateTime.fromMillisecondsSinceEpoch(rawTimestamp); @@ -61,6 +65,7 @@ class Evaporasi { final jam = int.tryParse(parts[0]) ?? 0; final menit = int.tryParse(parts[1]) ?? 0; final detik = parts.length >= 3 ? (int.tryParse(parts[2]) ?? 0) : 0; + final now = DateTime.now(); timestamp = DateTime( now.year, now.month, @@ -74,27 +79,11 @@ class Evaporasi { } } - // Field di DB (dari info Anda): - // - evaporasi_mm - // - suhu_air - // - tinggi_air_cm - // Namun tetap toleran jika key berubah. - final evaporasiVal = json['evaporasi_mm'] ?? json['evaporasi'] ?? 0; - final suhuVal = json['suhu_air'] ?? json['suhu'] ?? 0; - final tinggiVal = json['tinggi_air_cm'] ?? json['tinggi_air'] ?? 0; - - double toDoubleSafe(dynamic v) { - if (v is num) return v.toDouble(); - if (v is String) return double.tryParse(v) ?? 0; - return 0; - } - return Evaporasi( - evaporasi: (json['evaporasi_mm'] ?? 0).toDouble(), - suhu: suhu, - tinggiAir: tinggi, - status: json['status'] ?? '', - timestamp: TimestampParser.parse(rawTime), // ✅ pakai TimestampParser + evaporasi: evaporasiVal, + suhu: suhuVal, + tinggiAir: tinggiVal, + timestamp: timestamp, ); } } diff --git a/test/widget_test.dart b/test/widget_test.dart index 7a974a8..a0f255e 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -5,12 +5,11 @@ // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. -import 'package:firebase_database/firebase_database.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:klimatologiot/app.dart'; import 'package:monitoring_repository/monitoring_repository.dart'; import 'package:user_repository/user_repository.dart'; -import '../lib/app.dart'; // import 'package:klimatologiot/main.dart'; @@ -49,31 +48,38 @@ class FakeUserRepository implements UserRepository { } class FakeMonitoringRepository implements MonitoringRepository { - get _db => null; - - // Satu fungsi untuk semua jenis sensor - // Kamu cukup masukkan "path" database-nya saja - @override - // Jika ingin mengambil data sekali saja (bukan stream) - Future getSensorSnapshot(String path) async { - return await _db.ref(path).get(); + Future getSensorSnapshot( + String path, + T Function(Map) mapper, + ) async { + return mapper({}); } @override - Stream getSensorStream(String path) { - // TODO: implement getSensorStream - throw UnimplementedError(); + Stream getSensorStream( + String path, + T Function(Map) mapper, + ) { + return const Stream.empty(); + } + + @override + Future> getSensorHistory( + String path, + T Function(Map) mapper, + ) async { + return []; } } void main() { testWidgets('App loads', (WidgetTester tester) async { final fakeRepo = FakeUserRepository(); - final fakeMonitoring = FakeUserRepository(); + final fakeMonitoring = FakeMonitoringRepository(); // Build our app and trigger a frame. await tester.pumpWidget( - MyApp(fakeRepo, fakeMonitoring as MonitoringRepository), + MyApp(fakeRepo, fakeMonitoring), ); await tester.pump();