首页 > 解决方案 > 导航未定义名称上下文

问题描述

我目前正在查看在我的应用程序中使用不同屏幕进行导航,到目前为止,我可以成功地从LoginScreen导航到EventsScreen。问题是在 EventsScreen 中有一个按钮,如果单击它应该带我到LoginScreen,这就是我拥有的代码。

在我的events_screen.dart文件 中在此处输入图像描述

在我的app.dart文件MaterialApp小部件中,我的路线为 在此处输入图像描述

单击假日平面按钮时,它不会将我带到“/HolidayScreen”路线。

如何解决[dart] Undefined name 'context'

events_screen.dart

import 'package:flutter/material.dart';
import 'holiday.dart';

class EventsScreen extends StatelessWidget {
  Widget build(context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.white,
        body: Container(
          alignment: Alignment.center,
          margin: EdgeInsets.all(20.0),
          child: ListView(
            children: <Widget>[ 
              Container(margin: EdgeInsets.only(bottom: 20.0)),
              eventsButton(),
              Container(margin: EdgeInsets.only(bottom: 20.0)),
            ],
          ),

        ),
      ),
    );
  }


  Widget eventsButton() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        FlatButton(
          color: Colors.red[800],
          onPressed: () {},
          child: Text(
            'Events',
            style: new TextStyle(color: Colors.white, fontWeight: FontWeight.normal),
          ),
        ),



        Container(margin: EdgeInsets.only(right: 20.0)),
        FlatButton(
          color: Colors.red[800],
          child: Text(
            'Holidays',
            style: new TextStyle(color: Colors.white, fontWeight: FontWeight.normal),
          ),
          onPressed: () {
            Navigator.pushNamed(context, "/Holiday");
          },       
        ),


        Container(margin: EdgeInsets.only(right: 20.0)),
        FlatButton(
          color: Colors.red[800],
          onPressed: () {},
          child: Text(
            'Flights',
            style: new TextStyle(color: Colors.white, fontWeight: FontWeight.normal),
          ),
        ),
      ],
    );
  }

}

标签: dartflutterflutter-layoutflutter-test

解决方案


很简单,只需将 BuildContext 传递给您的eventsButton方法

       Widget build(context) {
        return MaterialApp(
          home: Scaffold(
            backgroundColor: Colors.white,
            body: Container(
              alignment: Alignment.center,
              margin: EdgeInsets.all(20.0),
              child: ListView(
                children: <Widget>[ 
                  Container(margin: EdgeInsets.only(bottom: 20.0)),
                  eventsButton(context),
                  Container(margin: EdgeInsets.only(bottom: 20.0)),
                ],
              ),

            ),
          ),
        );
      }

并在您的方法中添加一个参数

    Widget eventsButton(BuildContext context) {
      return Row(
        mainAxisAlignment: MainAxisAlignment

     //...

更新

并改变这个:

  Navigator.pushNamed(context, "/Holiday");

对此:

   Navigator.pushNamed(context, "/HolidayScreen");

因为您的路线名称是 HolidayScreen 而不是 Holiday


推荐阅读