How to prevent the user from returning to the login screen after logging into the flutter?

Asked

Viewed 1,700 times

2

I have the following login widget that after the request is successfully made, it adds on the navigation stack to the home screen and removes the login screen.

If I try to get back from home screen to login the app is minimized. However, when I open again the app opens the login screen.

In my main.dart is checked if it has a token. If it does, it is directed to the home screen. If not, to the login screen.

  checkHome() async {
    // Read value
    String token = await storage.read(key: 'token');

    return token;
  }

  @override
  void initState(){
    super.initState();
    checkHome();
  }


  @override
  Widget build(BuildContext context) {

    /// Chamada para solucionar o método.
    /// Nele também é acionado o `then()` que é
    /// que é onde pode ser capturado o retorno do futuro.
    checkHome().then((token) {
      temToken = token != null;
    });

    return MaterialApp(
      title: 'Cadê meu pet?',
      theme: ThemeData(primarySwatch: Colors.yellow),
      /// Declaração do ternário para escolher qual page exibir
      home: temToken ? HomePage() : LoginPage(),
      routes: routes
    );
  }
}

This is the way I handle the navigation stack on login:

if (response.statusCode == 202) {
      Map<String, dynamic> map = json.decode(response.body);
      // Write values
      await storage.write(key: 'token', value: map['token']);
      await storage.write(key: 'foto', value: map['foto']);
      await storage.write(key: 'nomeUsuario', value: map['nomeUsuario']);
      Navigator.pushNamed(context, '/home');
      Navigator.popUntil(context, ModalRoute.withName('/login'));
 }

My setting:

I have a token, so I’m on the home screen; I click on the button "back" android; The app is minimized; I open the app again; The login screen is displayed.

By possessing token, the expected is that when the app is minimized, when returning open the home screen.

  • 1

    I recommend that you post a complete code so that it can be reproduced so that you can fully understand the context of your problem and point out where it can be optimized. In the current way that posted it is difficult to understand what was actually encoded in the methods and how you organized everything. Another detail is also posting what you have already tried to understand the problem, such as what you noticed when debugging your app?

  • @Leonardo thanks for the feedback, I’ll try to organize better

2 answers

2

You can clear the navigation stack after successfully logging in.

Use your Navigator this way for the new screen:

Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context)=>HomePage()),(Route<dynamic> route) => false);

This way you clear the navigation and if the user tries to come back will minimize the application.

2


Your structure doesn’t work because you’re working with a Future and you’re not doing the right thing... You can try two ways

1st form

Add the setState() and see if it works as you wish

  checkHome().then((token) {
    setState((){
      temToken = token != null;
    });
  });

2nd form

Make use of the FutureBuilder()

Future<bool> checkHome() async {
    String token = await storage.read(key: 'token');
    return token != null;
  }

  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      title: 'Cadê meu pet?',
      theme: ThemeData(primarySwatch: Colors.yellow),
      /// Declaração do ternário para escolher qual page exibir
      home: FutureBuilder(
        future: checkHome(),
        builder: (context, snapshot){
          if (!snpashot.hasData)
            return Center(child: CircularProgressIndicator());

          return snpashot.data ? HomePage() : LoginPage();
        }
      ),
      routes: routes
    );
  }
  • 1

    Thank you. I’ll test soon and give you a feedback

Browser other questions tagged

You are not signed in. Login or sign up in order to post.