Reputation: 2175
I have a Flutter app that uses Riverpod as State management and Firebase Realtime database.
Everytime a user launch the app, i need to fetch the current user to ensure where to route the user (landing page, login page, admin page or home page).
So there are two ways that i figured i could do this and i need advice on which one is better (or if both are bad):
Method 1 - Load it in the main before launching my widget:
void main() async {
// Declare a glam user variable
GlamUser? glamUser;
// Ensure the widgets are initialized
WidgetsFlutterBinding.ensureInitialized();
// Load firebase
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the shared preferences
final prefs = await SharedPreferences.getInstance();
try {
// Get the current user from firebase
final user = AuthService().currentUser;
// If the user is not null, get the user from the database
if (user != null) {
glamUser = await GlamUsersImpl().getById(user.uid);
}
} catch (e) {
print("Error $e");
}
// Run the main app
runApp(
ProviderScope(
overrides: [
// Intialize the app settings repository
settingsRepositoryProvider.overrideWithValue(
AppSettingsImpl(prefs),
),
],
child: MyApp(
glamUser: glamUser,
),
),
);
}
Why i do this here because the getUser method needs to be async and this seems to be a good place to do it.
Method 2 - Load it in my widget before MaterialApp:
class MyApp extends ConsumerWidget {
// Constructor
const MyApp({
super.key,
});
// Creare
@override
Widget build(BuildContext context, WidgetRef ref) {
// Get the user
final glamUser = ref.watch(getGlamUser).when(data, error, loading);
Method 2 seems to have more work in it because i need to handle loading, error and loaded widget views and then return my MaterialApp based on this but it seems better when it comes to error handling
Method 1 seems to be more quickly but prone to error.
How would you guys do it ?
Upvotes: -1
Views: 46