Column 的子 CustomPainter 的大小变为 (0, 0)。
1) 当我们刚刚使用 CustomPaint 和 CustomPainter 时,我们期望的大小被传递给 CustomPainter,它按预期呈现。
2) 当我们使用 CustomPaint 和 CustomPainter 作为 Stack 的 child 时,我们期望的大小没有传递给 CustomPainter。
3) 但是当我们将它用作 SizedBox.expand 的子级时,我们期望的大小被传递给 CustomPainter 并被渲染。
4) 当我们使用 CustomPaint 和 CustomPainter 作为 Column 的 child 时,我们期望的大小没有传递给 CustomPainter。我们正在研究解决它的方法。
5) 但是,它的高度要么是 0.0,要么是无限大。我们希望它能够扩展到合适的大小。
import 'package:flutter/material.dart';
class TestWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
// 1) OK Size(360.0, 640.0)
// return CustomPaint(
// painter: TestPainter(),
// );
// 2) NG Size(0.0, 0.0)
// return Stack(
// children: <Widget>[
// CustomPaint(
// painter: TestPainter(),
// ),
// ],
// );
// 3) OK Size(360.0, 640.0)
// return Stack(
// children: <Widget>[
// SizedBox.expand(
// child: CustomPaint(
// painter: TestPainter(),
// ),
// ),
// ],
// );
// 4)5) NG BoxConstraints forces an infinite height.
// return Column(
// children: <Widget>[
// SizedBox.expand(
// child: CustomPaint(
// painter: TestPainter(),
// ),
// ),
// Text('test'),
// ],
// );
// 4)5) NG Size(0.0, 0.0)
// return Column(
// children: <Widget>[
// SizedBox(
// child: CustomPaint(
// painter: TestPainter(),
// ),
// ),
// Text('test'),
// ],
// );
// 4)5) Size(360.0, 0.0)
// return Column(
// children: <Widget>[
// SizedBox(
// width: double.infinity,
// child: CustomPaint(
// painter: TestPainter(),
// ),
// ),
// Text('test'),
// ],
// );
}
}
class TestPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
print(size);
Paint p = Paint();
p.color = Color.fromARGB(0xff, 0xff, 0x00, 0x00);
Rect rect = Rect.fromLTWH(0, 0, size.width, size.height);
canvas.drawRect(rect, p);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
我们希望 CustomPaint 和 CustomPainter 扩展到适当的大小,并且该大小将传递给 CustomPainter。
最佳答案
下面是CustomPaint()
的构造函数:
const CustomPaint({
Key key,
this.painter,
this.foregroundPainter,
this.size = Size.zero,
this.isComplex = false,
this.willChange = false,
Widget child,
}) : assert(size != null),
assert(isComplex != null),
assert(willChange != null),
super(key: key, child: child);
大小被忽略时被视为Size.zero
(意思是Size(0.0, 0.0)
),所以你需要将你想要的大小传递给'CustomPaint ()`.
return CustomPaint(
size: const Size(double.infinity, double.infinity), // or whatever size you want it to be
painter: TestPainter(),
);
至于在Column
中扩展小部件,请使用Expanded
而不是SizedBox.expand
。
关于dart - 我们如何将尺寸传递给 CustomPaint?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53941079/