我有一个非常奇怪的东西:
以下代码使用CustomPaint
绘制一个矩形。这个版本运行良好
import 'package:flutter/material.dart';
class MyApp extends StatefulWidget {
@override
_ MyAppState createState() => _ MyAppState();
}
class _MyAppState extends State<MyApp> {
EmbeddedPainter _painter;
@override
void initState() {
super.initState();
_painter = EmbeddedPainter();
}
@override
Widget build(BuildContext context) {
return Container(
child: ClipRect(
child: CustomPaint(
painter: _painter
),
),
);
}
}
然后,一旦我将这个CustomPaint
放入Column
小部件中,我就看不到绘制的矩形了。
import 'package:flutter/material.dart';
class MyApp extends StatefulWidget {
@override
_ MyAppState createState() => _ MyAppState();
}
class _MyAppState extends State<MyApp> {
EmbeddedPainter _painter;
@override
void initState() {
super.initState();
_painter = EmbeddedPainter();
}
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
ClipRect(
child: CustomPaint(
painter: _painter
),
),
],
)
);
}
}
画家看起来像这个
class EmbeddedPainter extends CustomPainter with ChangeNotifier {
var _paint = Paint()
..strokeJoin = StrokeJoin.miter
..strokeWidth = 1.0
..color = Colors.green
..style = PaintingStyle.fill;
@override
void paint(Canvas canvas, Size size) {
canvas.drawRect(Rect.fromLTWH(50, 50, 100, 100), _paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => true;
void update(Color color0, Color color1) {
// draw
notifyListeners();
}
}
自己解决了:
ClipRect
必须用一定尺寸的容器包装,例如SizedBox
。
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
SizedBox(
width: 500,
height: 300,
child: ClipRect(
child: CustomPaint(
painter: _painter
),
),
)
],
)
);
}