0

My proposal is redirect if the user has an "admin role" or "user role".

Then the code of the login_page is

void _logIn() async {
    try {
      final newUser = await Auth().signInWithEmailAndPassword_xp(
        email: _controllerEmail.text,
        password: _controllerPassword.text,
      );
      if (newUser != null) {
        final docSnapshot =
            await Auth().getUserIfno(newUserMail: newUser.email.toString());
        if (docSnapshot.exists) {
          role = docSnapshot.data()!['role'];
          if (role == "admin1") {
            Navigator.of(context).pushNamed(admin_page.route);
          } else {
            Navigator.of(context).pushNamed(user_page.route);
          }
        }
      } 
    } catch (e) {
      print(e);
    }
  }

It works as expected. But if anyone writes it in the browser, anyone can access "localhost:55352/#/admin_page"

see image

Then, I tried to secure the admin_page if not "admin role" redirecting to user_page by this way:

class admin_page extends StatelessWidget {
  static const String route = '/admin_page';

  @override
  Widget build(BuildContext context) {
    if (role != "admin1") {
      Navigator.of(context).pushNamed(user_page.route);
    }
    return MaterialApp(
      title: 'admin_page',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('admin_page'),
        ),
      ),
    );
  }
}

The idea worked and the admin_page is redirected, but the Flutter project stops and thows this erros:

═╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ The following assertion was thrown building admin_page$(dirty): setState() or markNeedsBuild() called during build. This Overlay widget cannot be marked as needing to build because the framework is already in the process of building widgets.

see image

Is there any better practice or suggestion to secure single web-pages in Flutter web?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
xpe
  • 19
  • 5

1 Answers1

0

Found a solution here:

"setState() or markNeedsBuild() called during build" error trying to push a replacement in Navigator inside a Consumer widget (provider package)

Finally the code in the admin_page is:

class admin_page extends StatelessWidget {
  static const String route = '/admin_page';

  @override
  Widget build(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (role != "admin1") {
        Navigator.of(context).pushNamed("/");
      }
    });

    return Scaffold(
        appBar: AppBar(
          title: const Text('admin_page'),
        ),
        body: Center(
          child: Text(
            "admin_page",
            textAlign: TextAlign.center,
          ),
        ),
        );
  }
}

Problem solved. It now redirects as expected without advising error missage.

xpe
  • 19
  • 5