使用MediaQuery失败的App Bar高度计算



我正在构建一个应用程序,我想在其中显示4个容器,涵盖电话上的整个可用空间。

为此,我使用MediaQuery.of获得了屏幕的完整widthheight。我通过给每个容器的高度为0.25,使4个容器填充整个屏幕。

初始代码来到这里,正常工作:

import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(body: MyHomePage(title: 'Title')),
    );
  }
}
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return _buildMobileLayout(context);
  }
  Widget _buildMobileLayout(BuildContext context) {
    AppBar appBar = AppBar(
      title: Text("My App Title"),
    );
//    var newHeight =
//        (MediaQuery.of(context).size.height - appBar.preferredSize.height) *
//            0.25;
    var newHeight = (MediaQuery.of(context).size.height) * 0.25;
    return Scaffold(
      //appBar: appBar,
      body: Column(
        children: <Widget>[
          Container(
            width: MediaQuery.of(context).size.width,
            height: newHeight,
            child: Center(child: Text("Cont 1")),
          ),
          Container(
            width: MediaQuery.of(context).size.width,
            height: newHeight,
            child: Center(child: Text("Cont 2")),
          ),
          Container(
            width: MediaQuery.of(context).size.width,
            height: newHeight,
            child: Center(child: Text("Cont 3")),
          ),
          Container(
            width: MediaQuery.of(context).size.width,
            height: newHeight,
            child: Center(child: Text("Cont 4")),
          ),
        ],
      ),
    );
  }
}

您可以在上面的代码上看到,我还不包括Appbar,因为这是问题到来的时候。在没有Appbar的情况下,所有操作都可以,但是当我包括Appbar时,即使我要照顾它的高度,获得了新的总高度并将其分配在4个容器之间,我也会在最后一个容器上遇到Pixel Overflow的错误。<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<</p>

电话:华为P20 Pro。

而不是使用MediaQuery,您可以将每个小部件包装在Expanded中,并给它们相同的flex

 return Scaffold(
      //appBar: appBar,
      body: Column(
        children: <Widget>[
           Expanded(
            flex: 1,
            child: Center(child: Text("Cont 1")),
          ),
          Expanded(
            flex: 1,
            child: Center(child: Text("Cont 2")),
          ),
          Expanded(
            flex: 1,
            child: Center(child: Text("Cont 3")),
          ),
          Expanded(
            flex: 1,
            child: Center(child: Text("Cont 4")),
          ),
        ],
      ),
    );

最新更新