Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleaner hello world example #2

Open
chimon2000 opened this issue Apr 16, 2021 · 0 comments
Open

Cleaner hello world example #2

chimon2000 opened this issue Apr 16, 2021 · 0 comments

Comments

@chimon2000
Copy link

In hello_world_demo.dart, rather than creating a global NavStackController and assigning it in onGenerateStack, it may be better to wire up the keyboard navigation in scaffoldBuilder

Example implementation:

class HelloWorldDemo extends StatelessWidget {
  const HelloWorldDemo({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routeInformationParser: NavStackParser(),
      routerDelegate: NavStackDelegate(
        onGenerateStack: (context, nav) => PathStack(
          scaffoldBuilder: (context, child) =>
              KeyboardNavigationScaffold(child: child),
          routes: {
            ["/"]: HomeScreen().toStackRoute(),
            ["/messages"]: MessagesScreen().toStackRoute(),
            ["/profile"]: ProfileScreen().toStackRoute(),
          },
          transitionBuilder: (_, stack, anim1) =>
              FadeTransition(opacity: anim1, child: stack),
        ),
      ),
    );
  }
}

class KeyboardNavigationScaffold extends StatefulWidget {
  const KeyboardNavigationScaffold({
    Key? key,
    this.child,
  }) : super(key: key);

  final Widget? child;

  @override
  _KeyboardNavigationScaffoldState createState() =>
      _KeyboardNavigationScaffoldState();
}

class _KeyboardNavigationScaffoldState
    extends State<KeyboardNavigationScaffold> {
  late final _controller = NavStack.of(context);

  @override
  void initState() {
    super.initState();
    RawKeyboard.instance.addListener((value) {
      if (value is RawKeyDownEvent) {
        if (value.logicalKey == LogicalKeyboardKey.digit1)
          _controller.path = "/login";
        if (value.logicalKey == LogicalKeyboardKey.digit2)
          _controller.path = "/profile";
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(child: widget.child);
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant