#flutter #dart
Вопрос:
Я хочу создать приложение, содержащее 4 кнопки, и оно перейдет на другую страницу, если я нажму на кнопку. Но когда я использую навигатор, он показывает ошибку в context
.
import 'package:flutter/material.dart'; import 'package:mytestapp/LectureVideo.dart'; import 'package:path/path.dart'; void main() { runApp( MaterialApp( debugShowCheckedModeBanner: false, //hide debug sash at top right title: 'HomePage', home: MyApp(), ) ); } class MyApp extends StatelessWidget{ @override Widget build(BuildContext context) { double width = MediaQuery.of(context).size.width; //getting screen width return Scaffold( appBar: AppBar(title: Text('Welcome to EMTeach'), centerTitle: true, backgroundColor: Colors.lime[200], ), body: SafeArea( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Container(margin: EdgeInsets.only(bottom: 20.0)), FirstButton(width), Container(margin: EdgeInsets.only(bottom: 20.0)), SecondButton(width), Container(margin: EdgeInsets.only(bottom: 20.0)), ThirdButton(width), Container(margin: EdgeInsets.only(bottom: 20.0)), FourthButton(width), Container(margin: EdgeInsets.only(bottom: 20.0)), ], ), ), ); } Widget FirstButton(double width) { return Expanded( child: SizedBox( width: width - 20, child: RaisedButton( onPressed: () { Navigator.push( context, //error MaterialPageRoute(builder: (context) =gt; LectureVideo())); }, color: Colors.red, child: Text( "Lecture Video", textScaleFactor: 2.0, ), ), //fit: BoxFit.cover, ), ); } Widget SecondButton(double width) { return Expanded( child: SizedBox( width: width - 20, child: RaisedButton( onPressed: () {}, color: Colors.lightGreen, child: Text( "Application Video", textScaleFactor: 2.0, ), ), //fit: BoxFit.cover, ), ); } Widget ThirdButton(double width) { return Expanded( child: SizedBox( width: width - 20, child: RaisedButton( onPressed: () {}, color: Colors.lightBlue, child: Text( "List of Equation", textScaleFactor: 2.0, ), ), //fit: BoxFit.cover, ), ); } Widget FourthButton(double width) { return Expanded( child: SizedBox( width: width - 20, child: RaisedButton( onPressed: () {}, color: Colors.orange, child: Text( "List of Question", textScaleFactor: 2.0, ), ), //fit: BoxFit.cover, ), ); } }
Ответ №1:
проблема в том, что вы не передаете контекст, который является параметром функции сборки, своим кнопкам, попробуйте это:
Widget FirstButton(double width,BuildContext context ) { return Expanded( child: SizedBox( width: width - 20, child: RaisedButton( onPressed: () { Navigator.push( context, //error MaterialPageRoute(builder: (context) =gt; LectureVideo())); }, color: Colors.red, child: Text( "Lecture Video", textScaleFactor: 2.0, ), ), //fit: BoxFit.cover, ), ); }