我将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”。如何解决此问题?
最佳答案
您需要将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
的MyApp
。结果,MyApp
的BuildContext
没有以MaterialApp
作为父代。在您的情况下,由于
MyApp
需要MaterialApp
作为父类才能在该类中进行导航,因此您可以将Scaffold
提取到另一个类,并将MaterialApp
保留在MyApp
中。
关于flutter - 我将InkWell小部件连续放置,但无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60024626/