【问题标题】:flutter: CustomPaint widget turned blank when put in a Column颤振:CustomPaint 小部件在放入列时变为空白
【发布时间】:2020-07-28 12:51:11
【问题描述】:

我有一些非常奇怪的东西:

以下代码用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();
  }
}

【问题讨论】:

  • 控制台有什么错误吗?
  • 也许可以在CustomPaint 内给它一个Size size

标签: flutter dart custom-painting


【解决方案1】:

自己解决了:

ClipRect 必须用具有大小的容器包裹,例如 SizedBox


 @override
  Widget build(BuildContext context) {

    return Container(
          child: Column(
            children: <Widget>[
              SizedBox(
                width: 500,
                height: 300,
                child: ClipRect(
                  child: CustomPaint(
                      painter: _painter
                  ),
                ),
              )

            ],
          )
      );
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 2019-05-17
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多