Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to navigate in flutter during widget build?

Tags:

flutter

dart

I'm trying to detect that user is no longer authenticated and redirect user to login. This is how I'm doing it

  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _getData(context),
        builder: (context, snapshot) {
          try {
            if (snapshot.hasError && _isAuthenticationError(snapshot.error)) {
                Navigator.push(context, MaterialPageRoute(builder: (context) => LoginView()));
            }

Unfortunately doing navigation on build is not working. It throws this error

flutter: setState() or markNeedsBuild() called during build.
flutter: This Overlay widget cannot be marked as needing to build because the framework is already in the
flutter: process of building widgets.  A widget can be marked as needing to be built during the build 

I cannot just return LoginView widget since parent widget containts app bar and floating button and login view needs to be displayed without these controlls.. I need to navigate.

Is it possible to do it?

like image 592
StackOverflower Avatar asked Jan 18 '20 19:01

StackOverflower


People also ask

How does the Navigator work in Flutter?

Using the Navigator API In Flutter these elements are called routes and they're managed by a Navigator widget. The navigator manages a stack of Route objects and provides two ways for managing the stack, the declarative API Navigator. pages or imperative API Navigator. push and Navigator.


1 Answers

Wrap it in Future.microtask. This will schedule it to happen on the next async task cycle (i.e. after build is complete).

Future.microtask(() => Navigator.push(
  context, 
  MaterialPageRoute(builder: (context) => LoginView())
));
like image 156
Abion47 Avatar answered Sep 25 '22 21:09

Abion47