首页 > 解决方案 > 控制台在运行时给出未定义的名称上下文(颤动)

问题描述

我是新手,不知道为什么会收到这种错误。Undefined name Context我该如何解决它以及任何其他与颤振相关的建议都会很棒。我什至不知道这是什么意思。谢谢

void main() {
       runApp(
         MaterialApp(
           home: Scaffold(
             appBar: AppBar(
               title: Text('Welcome to, Dice Game'),
             ),
             backgroundColor: Colors.blue,
             body: DicePage(),
             drawer: Drawer(
               child: ListView(
                 children: <Widget>[
                   ListTile(
                     title: SafeArea(
                       child: Text('About us',style: TextStyle(
                           fontSize: 20.0,
                           fontWeight: FontWeight.w200
                       ),),
                     ),
                     onTap: (){
                       Navigator.push(
                         context,  //this line is causing the error
                         MaterialPageRoute(builder: (context) => SecondRoute()),
                       );
                     },
                   ),
                 ],
               ),
             ),
           ),
         ),
       );
     }

标签: flutterdart

解决方案


您应该将 MaterialApp 包装在 StatelessWidget 或 State 类中,如下所示:


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


class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Welcome to, Dice Game'),
        ),
        backgroundColor: Colors.blue,
        body: Stack(children: [],),
        drawer: Drawer(
          child: ListView(
            children: <Widget>[
              ListTile(
                title: SafeArea(
                  child: Text('About us',style: TextStyle(
                      fontSize: 20.0,
                      fontWeight: FontWeight.w200
                  ),),
                ),
                onTap: (){
                  Navigator.push(
                    context,  //this line is causing the error
                    MaterialPageRoute(builder: (context) => SecondRoute()),
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

推荐阅读