首页 > 解决方案 > 我们如何将尺寸传递给 CustomPaint?

问题描述

列子的 CustomPainter 的大小变为 (0, 0)。

1)当我们刚刚使用CustomPaint和CustomPainter时,我们期望的大小被传递给CustomPainter,它按预期渲染。

2) 当我们使用 CustomPaint 和 CustomPainter 作为 Stack 的孩子时,我们期望的大小没有传递给 CustomPainter。

3) 但是当我们将它用作 SizedBox.expand 的子项时,我们期望的大小被传递给 CustomPainter 并被渲染。

4) 当我们使用 CustomPaint 和 CustomPainter 作为 Column 的孩子时,我们期望的大小没有传递给 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。

标签: dartflutter

解决方案


下面是 的构造函数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


推荐阅读