【问题标题】:How to have a dynamically sized CustomPainter in Flutter?如何在 Flutter 中拥有动态大小的 CustomPainter?
【发布时间】:2021-12-26 22:48:39
【问题描述】:

考虑Flutter docs中的以下代码:

CustomPaint(
  painter: Sky(),
  child: const Center(
    child: Text(
      'Once upon a time...',
      style: TextStyle(
        fontSize: 40.0,
        fontWeight: FontWeight.w900,
        color: Color(0xFFFFFFFF),
      ),
    ),
  ),
)

我不想要文本小部件。

我不希望 CustomPaint 小部件被子小部件遮挡。

我还希望 CustomPaint 小部件填充任何可用空间。

我认为解决方案是将 Text 小部件替换为 Expanded 之类的 BLANK 小部件。

但是,我尝试了 Expanded、Container、Spacer 和 Space 小部件的各种组合,但总是出错或大小为零。

谢谢!

【问题讨论】:

  • 您想根据您的自定义绘图设置动态尺寸吗?还是覆盖整个屏幕?
  • 感谢您的努力。我更新了问题。希望这可以解释。

标签: flutter layout widget custom-painting custom-painter


【解决方案1】:

您可以通过MediaQuery获取屏幕的高度和宽度并使用它们

final width = MediaQuery.of(context).size.width;
    final height = MediaQuery.of(context).size.height;
    return CustomPaint(
      size: Size(width,height),
      painter: Sky(),
      child: const Center(
        child: Text(
          'Once upon a time...',
          style: TextStyle(
            fontSize: 40.0,
            fontWeight: FontWeight.w900,
            color: Color(0xFFFFFFFF),
          ),
        ),
      ),
    );

【讨论】:

    【解决方案2】:

    你是怎么做的:

    Expanded(
      child: CustomPaint(
        painter: MyCustomPainter(),
        size: Size.infinite,
    
      ),
    ),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      • 2019-10-16
      • 1970-01-01
      • 2022-12-25
      • 2020-05-28
      • 2018-11-17
      • 2018-12-23
      相关资源
      最近更新 更多