Flutter:导航问题

时间:2019-02-07 07:40:21

标签: android dart flutter

我无法导航显示错误信息的屏幕'在不包含导航器的上下文中请求的导航器操作,我尝试了许多解决方案,其中在Builder中使用了导航器, stateless个小部件,但是在override中的intiSate方法中,几秒钟后会自动完成导航。我的目标是几秒钟后浏览屏幕。

class Splash extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return testWidget;
      }
    }

Widget testWidget = new MediaQuery(
    data: new MediaQueryData(),
    child: new MaterialApp( title: 'xxxxxxxxxxxxx',
      home: SplashScreen(),
      debugShowCheckedModeBanner: false,
      routes: <String, WidgetBuilder>{
        '/login': (BuildContext context) => new Login(),
      },
    )

);

class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => new _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen>  {
  @override
  Future initState ()  {
    super.initState();
   new Future.delayed(
        const Duration(seconds: 2), () => Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => Login()),
        ));
  }
  @override
  Widget build(BuildContext context) {

    return(Scaffold(
      body: Container(
        height: double.infinity,
        width: double.infinity,
        child: Image.asset('assets/images/crop.jpg',fit:BoxFit.fill),
      ),
    ));
    //build
  }
}

显示错误

  

导航器操作请求的上下文不包含导航器。   用于从导航器推送或弹出路由的上下文必须是作为导航器小部件的后代的小部件的上下文。

1 个答案:

答案 0 :(得分:1)

已更正代码:

  

MaterialApp应该始终是所有Widget的Root Widget。   这样,导航器始终可用。

void main() => runApp(Splash());

class Splash extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: testWidget,
      debugShowCheckedModeBanner: false,
    );
  }
}

Widget testWidget =
    new MediaQuery(data: new MediaQueryData(), child: new SplashScreen());

class SplashScreen extends StatefulWidget {
  @override
  _SplashScreenState createState() => new _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    super.initState();
    Future.delayed(
        const Duration(seconds: 2),
        () => Navigator.pushReplacement(
              context,
              MaterialPageRoute(builder: (context) => Login()),
            ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Spalsh'),),
      body: Container(
        height: double.infinity,
        width: double.infinity,
//        child: Image.asset('assets/images/crop.jpg', fit: BoxFit.fill),
      ),
    );
    //build
  }
}

class Login extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login Page'),
      ),
      body: Container(),
    );
  }
}