sementara

This commit is contained in:
kleponijo 2026-05-23 21:07:41 +07:00
parent d7db4ece12
commit 87507f1f13
11 changed files with 218 additions and 142 deletions

View File

@ -37,4 +37,3 @@ class MyApp extends StatelessWidget {
); );
} }
} }
// sadadda

View File

@ -1,9 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:klimatologiot/blocs/authentication_bloc/authentication_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:klimatologiot/screens/auth/views/welcome_screen.dart'; import 'screens/splash/views/splash_screen.dart';
import 'package:klimatologiot/screens/home/views/home_screen.dart';
class MyAppView extends StatelessWidget { class MyAppView extends StatelessWidget {
const MyAppView({super.key}); const MyAppView({super.key});
@ -11,32 +8,25 @@ class MyAppView extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MaterialApp( return MaterialApp(
title: 'Klimatologi', title: 'Klimatologi',
debugShowCheckedModeBanner: false, debugShowCheckedModeBanner: false,
localizationsDelegates: const [ localizationsDelegates: const [
GlobalMaterialLocalizations.delegate, GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate, GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate, GlobalCupertinoLocalizations.delegate,
], ],
supportedLocales: const [ supportedLocales: const [
Locale('id', 'ID'), Locale('id', 'ID'),
Locale('en'), Locale('en'),
], ],
theme: ThemeData( theme: ThemeData(
colorScheme: ColorScheme.light( colorScheme: ColorScheme.light(
surface: Colors.grey.shade100, surface: Colors.grey.shade100,
onSurface: Colors.black, onSurface: Colors.black,
primary: Colors.blue, primary: Colors.blue,
onPrimary: Colors.white), onPrimary: Colors.white),
), ),
home: BlocBuilder<AuthenticationBloc, AuthenticationState>( home: const SplashScreen(),
builder: ((context, state) { );
if (state.status == AuthenticationStatus.authenticated) {
return HomeScreen();
} else {
return WelcomeScreen();
}
}),
));
} }
} }

View File

@ -12,7 +12,6 @@ void main() async {
options: DefaultFirebaseOptions.currentPlatform, options: DefaultFirebaseOptions.currentPlatform,
); );
await initializeDateFormatting('id_ID', null); await initializeDateFormatting('id_ID', null);
await Future.delayed(const Duration(seconds: 2));
runApp(MyApp( runApp(MyApp(
FirebaseUserRepo(), FirebaseUserRepo(),
FirebaseMonitoringRepo(), FirebaseMonitoringRepo(),

View File

@ -28,7 +28,5 @@ class SignInBloc extends Bloc<SignInEvent, SignInState> {
emit(SignInFailure()); emit(SignInFailure());
} }
}); });
on<SignOutRequired>((event, emit) async => await _userRepository.logOut());
} }
} }

View File

@ -1,6 +1,7 @@
import 'package:bloc/bloc.dart'; import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart'; import 'package:equatable/equatable.dart';
import 'package:user_repository/user_repository.dart'; import 'package:user_repository/user_repository.dart';
import 'package:firebase_auth/firebase_auth.dart';
part 'sign_up_event.dart'; part 'sign_up_event.dart';
part 'sign_up_state.dart'; part 'sign_up_state.dart';
@ -12,13 +13,27 @@ class SignUpBloc extends Bloc<SignUpEvent, SignUpState> {
on<SignUpRequired>((event, emit) async { on<SignUpRequired>((event, emit) async {
emit(SignUpProcess()); emit(SignUpProcess());
try { try {
MyUser myUser = await _userRepository.signUp(event.user, event.password);
await _userRepository.signUp(event.user, event.password);
await _userRepository.setUserData(myUser);
emit(SignUpSuccess()); emit(SignUpSuccess());
} catch (e) { } catch (e) {
emit(SignUpFailure(e.toString())); String message = 'Terjadi kesalahan. Coba lagi.';
if (e is FirebaseAuthException) {
switch (e.code) {
case 'email-already-in-use':
message = 'Email sudah terdaftar.';
break;
case 'weak-password':
message = 'Password terlalu lemah.';
break;
case 'invalid-email':
message = 'Format email tidak valid.';
break;
}
}
emit(SignUpFailure(message));
} }
}); });
} }
} }
// 2 / 5

View File

@ -39,12 +39,6 @@ class _SignInScreenState extends State<SignInScreen> {
if (state is SignInFailure) { if (state is SignInFailure) {
setState(() => _errorMsg = 'Email atau password salah. Coba lagi.'); setState(() => _errorMsg = 'Email atau password salah. Coba lagi.');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(_errorMsg!),
backgroundColor: Colors.red,
),
);
} else if (state is SignInSuccess) { } else if (state is SignInSuccess) {
setState(() => _errorMsg = null); setState(() => _errorMsg = null);
} }
@ -159,7 +153,7 @@ class _SignInScreenState extends State<SignInScreen> {
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
// Tombol Google — hanya muncul ketika tidak loading // // Tombol Google — hanya muncul ketika tidak loading
SizedBox( SizedBox(
width: MediaQuery.of(context).size.width * 0.5, width: MediaQuery.of(context).size.width * 0.5,
child: TextButton.icon( child: TextButton.icon(

View File

@ -1,6 +1,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:user_repository/user_repository.dart'; import 'package:user_repository/user_repository.dart';
import 'package:klimatologiot/blocs/authentication_bloc/authentication_bloc.dart'; // ← tambah
import 'package:klimatologiot/screens/home/views/home_screen.dart';
import '../blocs/sign_in_bloc/sign_in_bloc.dart'; import '../blocs/sign_in_bloc/sign_in_bloc.dart';
import '../blocs/sign_up_bloc/sign_up_bloc.dart'; import '../blocs/sign_up_bloc/sign_up_bloc.dart';
@ -32,54 +34,65 @@ class _WelcomeScreenState extends State<WelcomeScreen>
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return BlocListener<AuthenticationBloc, AuthenticationState>(
backgroundColor: Colors.white, listener: (context, state) {
body: SafeArea( if (state.status == AuthenticationStatus.authenticated) {
child: Column( Navigator.pushAndRemoveUntil(
children: [ context,
const SizedBox(height: 24), MaterialPageRoute(builder: (_) => HomeScreen()),
Padding( (route) => false, // hapus semua route lama (termasuk SplashScreen)
padding: const EdgeInsets.symmetric(horizontal: 50.0), );
child: TabBar( }
controller: tabController, },
unselectedLabelColor: child: Scaffold(
Theme.of(context).colorScheme.onSurface.withOpacity(0.5), backgroundColor: Colors.white,
labelColor: Theme.of(context).colorScheme.onSurface, body: SafeArea(
tabs: const [ child: Column(
Padding( children: [
padding: EdgeInsets.all(12.0), const SizedBox(height: 24),
child: Text('Sign In', style: TextStyle(fontSize: 18)), Padding(
), padding: const EdgeInsets.symmetric(horizontal: 50.0),
Padding( child: TabBar(
padding: EdgeInsets.all(12.0), controller: tabController,
child: Text('Sign Up', style: TextStyle(fontSize: 18)), unselectedLabelColor:
), Theme.of(context).colorScheme.onSurface.withOpacity(0.5),
], labelColor: Theme.of(context).colorScheme.onSurface,
), tabs: const [
), Padding(
// FIX: Expanded supaya TabBarView mengisi sisa tinggi layar padding: EdgeInsets.all(12.0),
// dengan ini scroll di dalam tab bisa berjalan normal child: Text('Sign In', style: TextStyle(fontSize: 18)),
Expanded(
child: TabBarView(
controller: tabController,
children: [
BlocProvider<SignInBloc>(
create: (context) =>
// FIX: akses UserRepository langsung, bukan via AuthBloc
SignInBloc(context.read<UserRepository>()),
child: const SignInScreen(),
),
BlocProvider<SignUpBloc>(
create: (context) =>
SignUpBloc(context.read<UserRepository>()),
child: SignUpScreen(
onSignInTap: () => tabController.animateTo(0),
), ),
), 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<SignInBloc>(
create: (context) =>
// FIX: akses UserRepository langsung, bukan via AuthBloc
SignInBloc(context.read<UserRepository>()),
child: const SignInScreen(),
),
BlocProvider<SignUpBloc>(
create: (context) =>
SignUpBloc(context.read<UserRepository>()),
child: SignUpScreen(
onSignInTap: () => tabController.animateTo(0),
),
),
],
),
),
],
),
), ),
), ),
); );

View File

@ -1,8 +1,10 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../auth/views/welcome_screen.dart'; import 'package:klimatologiot/blocs/authentication_bloc/authentication_bloc.dart';
import 'package:klimatologiot/screens/auth/views/welcome_screen.dart';
import 'package:klimatologiot/screens/home/views/home_screen.dart';
class SplashScreen extends StatefulWidget { class SplashScreen extends StatefulWidget {
const SplashScreen({super.key}); const SplashScreen({super.key});
@ -15,15 +17,36 @@ class _SplashScreenState extends State<SplashScreen> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_navigateAfterSplash();
}
Timer(const Duration(seconds: 3), () { Future<void> _navigateAfterSplash() async {
Navigator.pushReplacement( // Tunggu minimal 3 detik (efek splash)
context, await Future.delayed(const Duration(seconds: 3));
MaterialPageRoute( if (!mounted) return;
builder: (_) => const WelcomeScreen(),
), final bloc = context.read<AuthenticationBloc>();
);
}); // Kalau auth state masih unknown (Firebase belum resolve), tunggu dulu
AuthenticationState state = bloc.state;
if (state.status == AuthenticationStatus.unknown) {
state = await bloc.stream
.firstWhere((s) => s.status != AuthenticationStatus.unknown)
.timeout(
const Duration(seconds: 5),
onTimeout: () => const AuthenticationState.unauthenticated(),
);
}
if (!mounted) return;
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (_) => state.status == AuthenticationStatus.authenticated
? HomeScreen()
: WelcomeScreen(),
),
);
} }
@override @override
@ -35,7 +58,7 @@ class _SplashScreenState extends State<SplashScreen> {
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Image.asset( Image.asset(
'assets/images/logo.png', 'images/logo_klimatologi.png',
width: 140, width: 140,
), ),
const SizedBox(height: 24), const SizedBox(height: 24),

View File

@ -1,16 +1,14 @@
class MyUserEntity { class MyUserEntity {
String userId; final String userId;
String email; final String email;
String name; final String name;
bool hasActiveCart; final bool hasActiveCart;
MyUserEntity ({ MyUserEntity({
required this.userId, required this.userId,
required this.email, required this.email,
required this.name, required this.name,
required this.hasActiveCart, required this.hasActiveCart,
}); });
Map<String, Object?> toDocument() { Map<String, Object?> toDocument() {
@ -19,17 +17,17 @@ class MyUserEntity {
'email': email, 'email': email,
'name': name, 'name': name,
'hasActiveCart': hasActiveCart, 'hasActiveCart': hasActiveCart,
}; };
} }
static MyUserEntity fromDocument(Map<String, dynamic> doc) { static MyUserEntity fromDocument(Map<String, dynamic> doc) {
return MyUserEntity( return MyUserEntity(
userId: doc['userId'] as String, userId: doc['userId'] as String? ?? '',
email: doc['email'] as String, email: doc['email'] as String? ?? '',
name: doc['name'] as String, name: doc['name'] as String? ?? '',
hasActiveCart: doc['hasActiveCart'] as bool, hasActiveCart: doc['hasActiveCart'] as bool? ?? false,
); );
} }
}
} // 3

View File

@ -3,14 +3,11 @@ import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_auth/firebase_auth.dart';
import 'package:rxdart/rxdart.dart'; import 'package:rxdart/rxdart.dart';
import 'package:user_repository/user_repository.dart'; import 'package:user_repository/user_repository.dart';
// Google Sign-In import di-disable sementara karena error analisis: import 'package:google_sign_in/google_sign_in.dart';
// "Target of URI doesn't exist: package:google_sign_in/google_sign_in.dart".
// Implementasi Google Sign-In (kecuali untuk web auth) akan dilewatkan.
import 'package:flutter/foundation.dart' show kIsWeb;
class FirebaseUserRepo implements UserRepository { class FirebaseUserRepo implements UserRepository {
final FirebaseAuth _firebaseAuth; final FirebaseAuth _firebaseAuth;
final _googleSignIn = GoogleSignIn();
final userCollection = FirebaseFirestore.instance.collection('users'); final userCollection = FirebaseFirestore.instance.collection('users');
FirebaseUserRepo({FirebaseAuth? firebaseAuth}) FirebaseUserRepo({FirebaseAuth? firebaseAuth})
@ -29,7 +26,12 @@ class FirebaseUserRepo implements UserRepository {
MyUserEntity.fromDocument(userData.data()!)); MyUserEntity.fromDocument(userData.data()!));
} else { } else {
// Data Firestore belum ada (seharusnya tidak terjadi dengan flow yang sudah diperbaiki) // Data Firestore belum ada (seharusnya tidak terjadi dengan flow yang sudah diperbaiki)
yield MyUser.empty; yield MyUser(
userId: firebaseUser.uid,
email: firebaseUser.email ?? '',
name: firebaseUser.displayName ?? '',
hasActiveCart: false,
);
} }
} catch (e) { } catch (e) {
log('Error fetching user data: $e'); log('Error fetching user data: $e');
@ -53,27 +55,29 @@ class FirebaseUserRepo implements UserRepository {
@override @override
Future<MyUser> signUp(MyUser myUser, String password) async { Future<MyUser> signUp(MyUser myUser, String password) async {
try { try {
UserCredential user = await _firebaseAuth.createUserWithEmailAndPassword( UserCredential credential =
email: myUser.email, password: password); await _firebaseAuth.createUserWithEmailAndPassword(
myUser.userId = user.user!.uid; email: myUser.email, password: password);
return myUser; final newUser = MyUser(
userId: credential.user!.uid,
email: myUser.email,
name: myUser.name,
hasActiveCart: false,
);
await setUserData(newUser);
return newUser;
} catch (e) { } catch (e) {
log(e.toString()); log(e.toString());
rethrow; rethrow;
} }
} }
// NOTE: Google Sign-In disabled because dependency import fails on this workspace.
// After google_sign_in issue resolved, restore the implementation.
@override @override
Future<void> logOut() async { Future<void> logOut() async {
// GoogleSignIn sementara di-skip karena error analisis import. await _googleSignIn.signOut();
await _firebaseAuth.signOut(); await _firebaseAuth.signOut();
} }
@override @override
Future<void> setUserData(MyUser myUser) async { Future<void> setUserData(MyUser myUser) async {
try { try {
@ -88,9 +92,34 @@ class FirebaseUserRepo implements UserRepository {
@override @override
Future<void> signInWithGoogle() async { Future<void> signInWithGoogle() async {
// Google Sign-In sementara dimatikan agar build tidak gagal. try {
// Setelah dependency google_sign_in benar-benar resolvable, bagian ini bisa dikembalikan. final googleUser = await _googleSignIn.signIn();
throw UnimplementedError('Google Sign-In disabled (analysis fix)'); if (googleUser == null) return; // user cancel
}
final googleAuth = await googleUser.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
final userCredential =
await _firebaseAuth.signInWithCredential(credential);
final firebaseUser = userCredential.user!;
final doc = await userCollection.doc(firebaseUser.uid).get();
if (!doc.exists) {
// User baru via Google — buat doc Firestore
final myUser = MyUser(
userId: firebaseUser.uid,
email: firebaseUser.email ?? '',
name: firebaseUser.displayName ?? '',
hasActiveCart: false,
);
await setUserData(myUser);
}
} catch (e) {
log(e.toString());
rethrow;
}
}
} }

View File

@ -1,25 +1,43 @@
import '../entities/entities.dart'; import '../entities/entities.dart';
class MyUser { class MyUser {
String userId; final String userId; // ← final semua
String email; final String email;
String name; final String name;
bool hasActiveCart; final bool hasActiveCart;
MyUser({ const MyUser({
required this.userId, required this.userId,
required this.email, required this.email,
required this.name, required this.name,
required this.hasActiveCart, required this.hasActiveCart,
}); });
static final empty = MyUser( static const empty = MyUser(
userId: '', userId: '',
email: '', email: '',
name: '', name: '',
hasActiveCart: false, hasActiveCart: false,
); );
bool get isEmpty => this == empty;
bool get isNotEmpty => this != empty;
// ← tambah copyWith agar bisa "ubah" tanpa mutasi
MyUser copyWith({
String? userId,
String? email,
String? name,
bool? hasActiveCart,
}) {
return MyUser(
userId: userId ?? this.userId,
email: email ?? this.email,
name: name ?? this.name,
hasActiveCart: hasActiveCart ?? this.hasActiveCart,
);
}
MyUserEntity toEntity() { MyUserEntity toEntity() {
return MyUserEntity( return MyUserEntity(
userId: userId, userId: userId,