我将Inkwell小部件放在一行中,并使每个小部件都展开。这是为了使两者都占据垂直屏幕的一半。
class MyApp extends StatefulWidget {
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container(
child: SafeArea(
child: Column(
children: <Widget>[
Expanded(
child: Row(
children: <Widget>[
Expanded(
child: Container (
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyApp2()),
);
},
)
)
),
Expanded (
child: Container(
color: Colors.grey
)
),
],
)
)
],
)
)
)
)
);
}
}
但是由于某种原因,InkWell白色小部件无法打开页面“ MyApp2”。我该如何解决这个问题?
答案 0 :(得分:1)
您需要将MaterialApp
小部件拆分为另一个类,如图所示。
import 'package:flutter/material.dart';
import 'MyApp2.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: SafeArea(
child: Column(
children: <Widget>[
Expanded(
child: Row(
children: <Widget>[
Expanded(child: Container(child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyApp2()),
);
},
))),
Expanded(child: Container(color: Colors.grey)),
],
))
],
))));
}
}
原因是您使用的是context
的父项MaterialApp
,上下文被传递到build
的{{1}}。结果,MyApp
的{{1}}没有MyApp
作为父项。
在您的情况下,由于BuildContext
需要MaterialApp
作为父类才能在该类中进行导航,因此您可以将MyApp
提取到另一个类,并将MaterialApp
留在{{1}中}。