Flutter Navigator not working

前端 未结 6 1105
死守一世寂寞
死守一世寂寞 2020-12-09 11:04

I have app with two screens, and I want to make push from 1st to second screen by pressing button.

Screen 1

import \'package:flutter/m         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 12:10

    There are two main reasons why the route cannot be found.

    1) The Route is defined below the context passed to Navigator.of(context) - scenario which @rmtmackenzie has explained

    2) The Route is defined on the sibling branch e.g.

    Root 
    
      -> Content (Routes e.g. Home/Profile/Basket/Search)
    
      -> Navigation (we want to dispatch from here)
    

    If we want to dispatch a route from the Navigation widget, we have to know the reference to the NavigatorState. Having a global reference is expensive, especially when you intend to move widget around the tree. https://docs.flutter.io/flutter/widgets/GlobalKey-class.html. Use it only where there is no way to get it from Navigator.of(context).

    To use a GlobalKey inside the MaterialApp define navigatorKey

    final navigatorKey = GlobalKey();
    
    Widget build(BuildContext context) => MaterialApp {
        navigatorKey: navigatorKey
        onGenerateRoute : .....
    };
    

    Now anywhere in the app where you pass the navigatorKey you can now invoke

    navigatorKey.currentState.push(....);
    

    Just posted about it https://medium.com/@swav.kulinski/flutter-navigating-off-the-charts-e118562a36a5

提交回复
热议问题