如何在 build()
期间获取小部件的大小和位置?方法?在下面的代码中,我想在 CustomPaint
中绘制矩形居中的小部件,占视口(viewport)剩余区域的一定百分比,即 Text
下方的所有区域小部件,标记为 (A)
.我可以从 MediaQuery
获得宽度,但是我如何获得 (A)
之后的剩余高度?我必须知道 Text
的位置小部件。
This answer不起作用,因为 Flutter 在尝试检索 RenderBox
时抛出异常在构建()期间。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('App')),
body: Column(children: [
Text('Test'), // (A) Get position of this
CustomPaint(
painter: DrawArea(MediaQuery.of(context).size),
size: Size(1000, 800),
),
]),
);
}
}
class DrawArea extends CustomPainter {
final Size viewportSize;
DrawArea(this.viewportSize);
@override
void paint(Canvas canvas, Size size) {
var paint = Paint()
..color = Colors.black
..strokeWidth = 1
..style = PaintingStyle.stroke;
double yOffset = (this.viewportSize.width - this.viewportSize.width * .95) / 2;
canvas.drawRect(Rect.fromLTWH(yOffset, 0, this.viewportSize.width * .95, 800), paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => true;
}
最佳答案
paint
的第二个参数方法是CustomPaint
的大小小部件。您只需要确保您的小部件尺寸合适。
制作 CustomPaint
占用 Column
中的剩余空间,您需要将其包装在 Expanded
中小部件:
body: Column(children: [
Text('Test'),
Expanded(
child: CustomPaint(
painter: DrawArea(),
size: Size.infinite, // make it as large as possible
),
),
]),
然后你可以使用传递的size
自定义画家中的参数:class DrawArea extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
var paint = Paint()
..color = Colors.black
..strokeWidth = 1
..style = PaintingStyle.stroke;
double xOffset = size.width * 0.025
double yOffset = size.height * 0.025
canvas.drawRect(Rect.fromLTWH(xOffset, yOffset, size.width * .95, size.height * .95), paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => true;
}
关于flutter - 在构建期间获取 Widget 的位置和大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64394705/