I have a Flutter app where I might navigate, using an external call, to a specific app page (UnlockAppsScreen). I can achieve this behaviour, but I would like to have a back arrow button in this page to navigate back to the main screen (AppScreen). To do this, I am trying to add the AppScreen to the stack before navigating to the UnlockAppsScreen.
I have this main.dart:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await initControllers();
// handle routing intent from foreground service
const platform = MethodChannel("testApp/route");
platform.setMethodCallHandler((call) async {
if (call.method == 'navigate') {
String route = call.arguments;
if (route == GetRoutes.appLock) {
Get.offNamed(GetRoutes.main);
Future.delayed(Duration(milliseconds: 100), () {
Get.toNamed(GetRoutes.appLock);
});
} else {
Get.toNamed(route);
}
}
});
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: selectedTheme,
initialRoute: GetRoutes.splash,
onGenerateRoute: GetRoutes.generateRoute,
);
}
}
class GetRoutes {
static const String splash = "/splash";
static const String main = "/main";
static const String appLock = "/app_lock";
static Route<dynamic>? generateRoute(RouteSettings settings) {
print(settings);
switch (settings.name) {
case splash:
return MaterialPageRoute(builder: (_) => SplashPage());
case main:
debugPrint("-----------------");
debugPrint("Navigating to main");
debugPrint("-----------------");
return MaterialPageRoute(builder: (_) => AppScreen());
case appLock:
debugPrint("-----------------");
debugPrint("Navigating to locked apps");
debugPrint("-----------------");
return MaterialPageRoute(builder: (_) => UnlockAppsScreen());
default:
return null;
}
}
}
The code opens the first page (from Get.offNamed(GetRoutes.main);
) but never opens the second page (supposedly from Get.toNamed(GetRoutes.appLock);
).
Do you have any ideas on how to solve this issue?
2
Answers
Use
navigator.pushReplacement
to go perticular screen.I understand you’re facing an issue with navigation. So, currently, you’ve three screens (1. Splash, 2. Home, 3. App Lock).
Your initial screen is the splash screen, and after a few seconds, you want to go either to the home screen or the app lock screen (based on your method channel).
So, here I wrote a sample code for you. Initially, it’ll navigate to the splash screen. After some delay, you navigate to the home screen (you can change it). And from the home screen, you can’t go back to the splash screen (obviously). From the home screen, you can go to the app lock screen. Once you enter the app lock screen, you can’t go back (obviously). If you pass, you can go to the home screen. If you fail, the app will close. You can’t go back to the home screen from the app lock screen.