由于某些原因,Stack
小部件不显示带有Container
的CustomPaint
。
但是如果从Stack
中删除,它会正常工作。我在这里想念什么?
class _DemoNavBar extends State<DemoNavBar> {
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home:
Stack(
children: <Widget>[
Container(child: CustomPaint(painter: CurvePainter()))
],
)
);
}
}
class CurvePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
var paint = Paint();
paint.color = Colors.green[800];
paint.style = PaintingStyle.fill;
var path = Path();
path.moveTo(0, size.height - 100);
path.lineTo(size.width * 0.5, size.height - 100);
path.quadraticBezierTo(size.width * 0.7, size.height, size.width * 0.9,
size.height - 100);
path.lineTo(size.width, size.height - 100);
path.lineTo(size.width, size.height);
path.lineTo(0, size.height);
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
谢谢!
正在检查CustomPaint
的来源
/// The size that this [CustomPaint] should aim for, given the layout
/// constraints, if there is no child.
///
/// Defaults to [Size.zero].
///
/// If there's a child, this is ignored, and the size of the child is used
/// instead.
所以,给它一个尺寸。其他解决方案包括:1)为Container
的父级CustomPaint
提供宽度和高度,以及2)为CustomPaint
的子级提供子级,该子级将忽略以下解决方案中提供的size
。
我检查了此代码,使其正常工作。size: MediaQuery.of(context).size
使用完整的屏幕尺寸。
void main() {
runApp(SO());
}
class SO extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DemoNavBar(),
);
}
}
class DemoNavBar extends StatefulWidget {
@override
_DemoNavBar createState() => _DemoNavBar();
}
class _DemoNavBar extends State<DemoNavBar> {
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
CustomPaint(
size: MediaQuery.of(context).size,
painter: CurvePainter(),
)
],
);
}
}
class CurvePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
var paint = Paint();
paint.color = Colors.green[800];
paint.style = PaintingStyle.fill;
var path = Path();
path.moveTo(0, size.height - 100);
path.lineTo(size.width * 0.5, size.height - 100);
path.quadraticBezierTo(size.width * 0.7, size.height, size.width * 0.9, size.height - 100);
path.lineTo(size.width, size.height - 100);
path.lineTo(size.width, size.height);
path.lineTo(0, size.height);
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
[现在,原因是由于Container
没有父级或子级来提供尺寸,因此它需要完整的屏幕尺寸,并且在没有Stack
的情况下也可以正常工作。当使用堆栈时,大小将为零,这将提供给自定义画家。