How can I pass values from main to the initial route of the app? I want to get the data from a sqflite database. I would prefer to make the initialization inside main function rather than the initial route and I am trying to figure out how to set the routes
main.dart
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await configureLocalTimeZone();
getIt.registerLazySingleton<UserRepositories>(() => UserRepositories());
getIt.registerSingleton<AppRouter>(AppRouter());
initializeNotifications();
DatabaseService databaseService = DatabaseService.instance;
final alarms = await databaseService.getAlarms();
AppRouter router = AppRouter();
runApp(MyApp(appRouter: router));
}
class MyApp extends StatelessWidget {
final AppRouter appRouter;
MyApp({Key? key, required this.appRouter}) : super(key: key);
@override
Widget build(BuildContext context) {
return MultiBlocProvider(providers: [
BlocProvider<UserBloc>(
create: (_) => UserBloc()..add(FetchUser()), // Add FetchUser event here
),
BlocProvider<LoginBloc>(
create: (_) => LoginBloc(userRepository: getIt<UserRepositories>()), // Add FetchUser event here
),
],
child: MaterialApp.router(
routerConfig: appRouter.config(),
)
);
}
}
AppRouter.dart
import 'package:auto_route/auto_route.dart';
import 'app_router.gr.dart';
@AutoRouterConfig(replaceInRouteName: 'Screen,Route')
class AppRouter extends $AppRouter {
@override
List<AutoRoute> get routes => [
AutoRoute(page: MainRoute.page, initial: true), // I WANT TO PASS ALARMS AND SERVICE TO MAIN SCREEN
];
}
2
Answers
Update the
MainRoute.page
to accept the required data, such asalarms
anddatabaseService
.Modify your
AppRouter
to accept these values and pass them to theMainRoute.page
.In your
main
function, pass thealarms
anddatabaseService
to theAppRouter
when you’re instantiating it.Now, when the
MainRoute.page
is created, it will receive both thealarms
anddatabaseService
as arguments.AutoRoute automatically detects and handles your page arguments for you, the generated route object will deliver all the arguments your page needs including path/query params.
e.g. The following page widget will take an argument of type Book.
Note: Default values are respected. Required fields are also respected and handled properly.
The generated BookDetailsRoute will deliver the same arguments to its corresponding page.