首页 > 解决方案 > 使用不包含 Navigator 的上下文请求的 Navigator 操作的解决方案

问题描述

我正在尝试添加一个图标按钮,该按钮将导航到另一条路线onPressed,并且在我运行应用程序之前没有错误,它向我显示了使用不包含导航器的上下文请求的导航器操作。我错过了什么?谢谢。我删除了脚手架内的代码以便能够发布这个问题

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

  @override
  Widget build(BuildContext context) {

    return MaterialApp(  
debugShowCheckedModeBanner: false,
    theme: ThemeData(fontFamily: 'Raleway'),

    home: Scaffold (

        ),

        body:
 Container(
          child:
 Column(children: [

           Text('Sign In', style: TextStyle(         
            color: Colors.orange,
            fontSize: 60.0) ),
             SizedBox(height:20,),
            TextField(
              
            decoration: InputDecoration(    
              border: OutlineInputBorder(),
              hintText: 'Email',
           
            ),
          ),
           TextField(
            decoration: InputDecoration(    
              border: OutlineInputBorder(),
              hintText: 'Password',
           
            ),
          ),
        SizedBox(height: 20,),
               ElevatedButton(  
                child: const Text('Sign In'),  
                  onPressed: null,  
              ),  

              SizedBox(height: 15,),
              Text('Forgot Password ?', style: TextStyle(fontSize: 15),)
            
              
          ],
          
          ),
          
          margin: EdgeInsets.only(top: 200),
        ),

      drawer: Drawer(

    child: ListView(
      padding: EdgeInsets.zero,
      children: <Widget>[
        DrawerHeader(
          decoration: BoxDecoration(
            color: Colors.purple,
          ),
          child: Image(image: AssetImage('Images/smsa logo.png'))
        ),




        ListTile(
          
          
          title: Text('My Account'),
          leading: IconButton(onPressed: (){Navigator.push(
            context,
          MaterialPageRoute(builder: (context) => new MyAccount() ));
           }, icon: Icon(Icons.account_circle)
          
        )),

标签: flutterdart

解决方案


问题是,即使MaterialApp您的小部件内部有 ,您也无法访问它context,而是无法访问在材料应用程序上方传递的上下文。要解决此问题,您必须MaterialApp在其自己的小部件中提取

这个你可以粘贴到DartPad上的例子向你展示了如何做到这一点:

import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) { // the context you access here has an MaterialApp above it
    return Text(
      'Hello, World!',
      style: Theme.of(context).textTheme.headline4,
    );
  }
}

推荐阅读