是否有一种简单的(非layoutbuilder)方法来相对于屏幕大小(宽/高)来调整元素的大小?例如:我如何设置CardView的宽度为屏幕宽度的65%。
它不能在构建方法内部完成(显然),所以它必须推迟到构建后。是否有一个更好的地方来放置这样的逻辑?
是否有一种简单的(非layoutbuilder)方法来相对于屏幕大小(宽/高)来调整元素的大小?例如:我如何设置CardView的宽度为屏幕宽度的65%。
它不能在构建方法内部完成(显然),所以它必须推迟到构建后。是否有一个更好的地方来放置这样的逻辑?
当前回答
使用LayoutBuilder小部件,它将为您提供约束,您可以使用这些约束来获得不包括AppBar和填充的高度。然后使用sizebox并使用来自LayoutBuilder的约束提供宽度和高度
return LayoutBuilder(builder: (context2, constraints) {
return Column(
children: <Widget>[
SizedBox(
width: constraints.maxWidth,
height: constraints.maxHeight,
...
其他回答
MediaQuery.of(context).size.width
使用缩放器定义布局宽度和高度的百分比
dependencies:
scaler: ^1.1.0+1
在pubspec中设置后。Yaml您可以通过以下代码使用此功能-
import 'package:scaler/scaler.dart';
导入后使用this -
import 'package:scaler/scaler.dart';
@override
Widget build(BuildContext context) {
/**
* Container with 25% width of screen
* and 25% height of screen
*/
return Container(
height: Scaler.height(0.25, context),
width: Scaler.width(0.25, context),
child: Container()
);
}
更详细地说
https://pub.dev/packages/scaler
首先确定屏幕的大小。
Size size = MediaQuery.of(context).size;
在此之后,你可以得到宽度,并将其与0.5相乘,以获得屏幕宽度的50%。
double width50 = size.width * 0.5;
但问题通常来自高度,默认情况下,当我们使用
double screenHeight = size.height;
我们得到的高度是全局高度,包括StatusBar + notch + AppBar高度。因此,为了获得设备的左侧高度,我们需要从总高度中减去填充高度(StatusBar + notch)和AppBar高度。我们是这样做的。
double abovePadding = MediaQuery.of(context).padding.top;
double appBarHeight = appBar.preferredSize.height;
double leftHeight = screenHeight - abovePadding - appBarHeight;
现在我们可以使用跟随来获得屏幕高度的50%。
double height50 = leftHeight * 0.5
您可以使用Align小部件。hightfactor和widthFactor参数乘以子部件的大小。下面是一个示例,它将创建一个具有%比例固定高度的小部件
Align(
alignment: Alignment.topCenter,
heightFactor: 0.63,
widthFactor: ,
child: Container(
width: double.infinity,
),
的宽度
double width = MediaQuery.of(context).size.width;
double yourWidth = width * 0.75;
身高
double height = MediaQuery.of(context).size.height;
double yourHeight = height * 0.75;
如果你不想要静态的高度和宽度,只需使用扩展小部件\
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatelessWidget(),
);
}
}
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Expanded Row Sample'),
),
body: Center(
child: Row(
children: <Widget>[
Expanded(
flex: 2,
child: Container(
color: Colors.amber,
height: 100,
),
),
Container(
color: Colors.blue,
height: 100,
width: 50,
),
Expanded(
child: Container(
color: Colors.amber,
height: 100,
),
),
],
),
),
);
}
}