Skip to content

[go_router] Figure out how to deal with inline GoRouter creation in MaterialApp.router #127206

Open

Description

@chunhtai

Is there an existing issue for this?

Use case

It is possible to create GoRouter inline with MaterialApp

void main() {
  runApp(MaterialApp.router(routerConfig: GoRouter()));
}

This will break hot reload because the gorouter will be recreate and loss all its state.

Another example is

class MyWidget extends StatelessWidget {
  @override
  Widget build(context) {
    return MaterialApp.router(routerConfig: GoRouter());
  }
}

Which would lose the state every time MyWidget is rebuilt.

Proposal

We should figure out how to avoid this situation. One idea can be writing a lint to warn user and advise putting the goRouter into a permanent variable

Activity

  1. added
    packageflutter/packages repository. See also p: labels.
    P3Issues that are less important to the Flutter project
    on May 19, 2023
  2. bizz84 commented on Jun 18, 2023

    @bizz84

    @chunhtai I got bitten by this also. I think having a linter rule for this would be a great step forward. 👍

  3. davidnwaneri commented on Aug 29, 2023

    @davidnwaneri

    A question.

    I have personally not had to experience this; I came across this while reading Andrea's article.
    So my question is, What if it was a final variable in a class?

    class AppRouter {
      final router = GoRouter();
    }

    And then:

    class MyWidget extends StatelessWidget {
      @override
      Widget build(context) {
    // This could also be a state variable if MyWidget was a stateful widget
    final appRouter = AppRouter();
        return MaterialApp.router(routerConfig: appRouter.router);
      }
    }
  4. chunhtai commented on Aug 29, 2023

    @chunhtai
    ContributorAuthor

    @davidnwaneri
    Unless it is a static variable, it would still be recreated when the build method is called.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3Issues that are less important to the Flutter projectp: go_routerThe go_router packagepackageflutter/packages repository. See also p: labels.team-ecosystemOwned by Ecosystem teamtriaged-ecosystemTriaged by Ecosystem team

    Type

    No type

    Projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions