dimanche 7 novembre 2021

Flutter Web - I can't show the page name on the url (navigationKey.currentState is NULL)

I need to show the user which page currently displayed in the url.

I've followed this tutorial (Flutter Web Advanced Navigation), the problem is it gives navigationKey.currentState is NULL when I try to navigate from navbar.

Bellow is the things a followed from the tutorial and I think it would be useful for you to help me with it. pls ask me if you need anything else :)

My NavigationService file:

class NavigationService {
  GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

  Future<dynamic> navigateTo(String? routeName, {dynamic arguments}) async {
    var returned;
    try {
      print("navigatorKey.currentState: ${navigatorKey.currentState}");
      returned = navigatorKey.currentState?.pushNamed(routeName!);
      print("returned val!!: $returned");
      return navigatorKey.currentState!.pushNamed(routeName!, arguments: arguments);
    }
    catch(e){
      print("ERROR!: $e");
      print("returned val!!: $returned");
    }
  }

  void goBack() {
    return navigatorKey.currentState!.pop();
  }
}

I used the try-catch and the output is:

navigatorKey.currentState: null
returned val!!: null
ERROR!: Unexpected null value.
returned val!!: null

My main file (Some code is deleted for readability):

void main() {
  setupLocator();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      builder: (context,child) => LayoutTemplate(child: child!),
      key: locator<NavigationService>().navigatorKey,
      onGenerateRoute: generateRoute,
      initialRoute: homeRoute,
    );
  }
}

Router file:

Route<dynamic> generateRoute(RouteSettings settings) {
  switch (settings.name) {
    case homeRoute:
      return _getPageRoute(const HomeBody(), settings);
    case aboutRoute:
      return _getPageRoute(const AboutUsBody(), settings);
    case projectsRoute:
      return _getPageRoute(const ProjectBody(), settings);
    case contactRoute:
      return _getPageRoute(const ContactUsBody(), settings);
    default:
      return _getPageRoute(const HomeBody(), settings);
  }
}
PageRoute _getPageRoute(Widget child, RouteSettings settings) {
  return MaterialPageRoute(builder: (context)=> child, settings: RouteSettings(name: settings.name),);
}

Navigation Function when you choose from the navbar items:

Future<void> _navigate(String router) async {
    controller.fling(velocity: -1);
    locator<NavigationService>().navigateTo(router);
    await Future.delayed(const Duration(milliseconds: 500), (){});
    controller.fling(velocity: 1);
  }



Aucun commentaire:

Enregistrer un commentaire