我将InkWell小部件连续放置,但无法正常工作

时间:2020-02-02 09:05:52

标签: flutter dart flutter-layout

我将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”。我该如何解决这个问题?

1 个答案:

答案 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}中}。