是否有一种简单的(非layoutbuilder)方法来相对于屏幕大小(宽/高)来调整元素的大小?例如:我如何设置CardView的宽度为屏幕宽度的65%。
它不能在构建方法内部完成(显然),所以它必须推迟到构建后。是否有一个更好的地方来放置这样的逻辑?
是否有一种简单的(非layoutbuilder)方法来相对于屏幕大小(宽/高)来调整元素的大小?例如:我如何设置CardView的宽度为屏幕宽度的65%。
它不能在构建方法内部完成(显然),所以它必须推迟到构建后。是否有一个更好的地方来放置这样的逻辑?
当前回答
您可以构建具有Flexible或Expanded子元素的列/行,这些子元素的flex值加起来等于您想要的百分比。
您可能还会发现AspectRatio小部件很有用。
其他回答
有几种可能性:
1-第一个是使用MediaQuery:
代码:
MediaQuery.of(context).size.width //to get the width of screen
MediaQuery.of(context).size.height //to get height of screen
使用示例:
Container(
color: Colors.yellow,
height: MediaQuery.of(context).size.height * 0.65,
width: MediaQuery.of(context).size.width,
)
输出:
2-使用FractionallySizedBox
创建一个小部件,将其子部件的大小设置为总可用空间的一小部分。
例子:
FractionallySizedBox(
widthFactor: 0.65, // between 0 and 1
heightFactor: 1.0,
child:Container(color: Colors.red
,),
)
输出:
3-使用其他小部件,如Expanded, Flexible和AspectRatio等。
有很多方法可以做到这一点。
1. 使用MediaQuery:返回设备全屏,包括应用程序栏,工具栏
Container(
width: MediaQuery.of(context).size.width * 0.50,
height: MediaQuery.of(context).size.height*0.50,
color: Colors.blueAccent[400],
)
2. 使用扩展:您可以按比例设置宽度/高度
Container(
height: MediaQuery.of(context).size.height * 0.50,
child: Row(
children: <Widget>[
Expanded(
flex: 70,
child: Container(
color: Colors.lightBlue[400],
),
),
Expanded(
flex: 30,
child: Container(
color: Colors.deepPurple[800],
),
)
],
),
)
3.其他人喜欢灵活和AspectRatio和分数大小的盒子
的宽度
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,
),
),
],
),
),
);
}
}
FractionallySizedBox也可能有用。 你也可以直接从MediaQuery.of(context)中读取屏幕宽度。大小,并在此基础上创建一个大小框
MediaQuery.of(context).size.width * 0.65
如果你真的想把屏幕的大小设置成一小部分不管布局是什么。
MediaQuery.of(context).size.width