gpt4 book ai didi

flutter - 使用MediaQuery的应用栏高度计算失败

转载 作者:行者123 更新时间:2023-12-03 03:40:23 24 4
gpt4 key购买 nike

我正在构建一个应用程序,我想在其中显示4个容器,这些容器覆盖了手机的整个可用空间。

为此,我将使用width获取完整的heightMediaQuery.of。通过使每个容器的高度为总高度的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个容器中,在最后一个容器上像素溢出也会导致错误。

电话:Huawei 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")),
),
],
),
);

关于flutter - 使用MediaQuery的应用栏高度计算失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56853538/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com