Search code examples
flutternavigationwidgetreusability

Looking up a deactivated widget's ancestor is unsafe. At this point the state of the widget's element tree is no longer stable. In flutter


Before you vote down please read full problem.

I am getting this error I know the reason behind this error, the reason is userDetails Widget is removed from the tree when the login screen is selected. The question is how I re-insert that widget back to Tree. I have tried each and every solution available on StackOverflow and GitHub but no solution worked for me. I have tried using new keyword and global key in the scaffold.

Main.dart

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var userPhoneNumber = prefs.getString('phoneNumber');
  var userAlternateNumber = prefs.getString('AlternateNumber');
  print(userPhoneNumber);
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
      .then((_) {
    runApp(
      MaterialApp(
        theme: ThemeData(
            textSelectionHandleColor: kOrangeColor, cursorColor: kOrangeColor),
        home: userPhoneNumber == null
            ? new LoginScreen()
            : (userAlternateNumber == null
                ? new UserDetails()
                : new HomeScreen()),
      ),
    );
  });
}

Function in LoginScreen.dart

 void pushToUserDetailsScreen(BuildContext context) async {
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => new UserDetails()));
  }

Solution

  • I suggest you use a temporary selector page, meaning that you can create a new page, and in this page you don't have to show any UI (Just black screen).

    What this would do is that it would decide what page you want to go next to, and this page would always be your homescreen, so when it's launched it will check if the phone number is null and would pushreplacement Login Screen , otherwise it would go to some other page.

    Also don't worry about it being a "Black Screen" as this all happens too fast (That depends on the conditions that allow you to decide the starting screen) and it directly takes you to the screen you want depending on the conditions you have.