且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在垂直(高度)和水平(宽度)方向上实现小部件的扩展

更新时间:2021-08-28 21:50:54

以下是针对您所遇到的问题的简化测试案例.解决方案是为您的Row赋予crossAxisAlignmentCrossAxisAlignment.stretch.否则,它将尝试确定CustomPaint的固有高度,该高度为零,因为它没有孩子.

Here is a reduced test case for the issue you are seeing. The solution is to give your Row a crossAxisAlignment of CrossAxisAlignment.stretch. Otherwise it will try to determine the intrinsic height of your CustomPaint which is zero because it doesn't have a child.

import 'package:flutter/material.dart';

// from https://***.com/questions/45875334/how-to-achieve-expansion-of-a-widget-in-both-vertical-height-and-horizontal-w

class MyCustomPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    // NOT using crossAxisAlignment: CrossAxisAlignment.stretch => width = 222.0, height=0.0
    // using crossAxisAlignment: CrossAxisAlignment.stretch     => width = 222.0, height=560.0
    print("width = ${size.width}, height=${size.height}");
    canvas.drawRect(Offset.zero & size, new Paint()..color = Colors.blue);
  }

  @override
  bool shouldRepaint(MyCustomPainter other) => false;
}
void main() {
  runApp(new MaterialApp(
    home: new Scaffold(
        body: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text('Above Paint'),
            // Expanded - because we are in Column, expand the
            //            contained row's height
            new Expanded(
              child: new Row(
                // The crossAxisAlignment is needed to give content height > 0
                //   - we are in a Row, so crossAxis is Column, so this enforces
                //     to "stretch height".
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  new Text('Left of Paint'),
                  // Expanded - because we are in Row, expand the
                  //           contained Painter's width
                  new Expanded(
                    child: new CustomPaint(
                      painter: new MyCustomPainter(),
                    ),
                  ),
                  new Text('Right of Paint'),
                ],
              ),
            ),
            new Text('Below Paint'),
          ],
        )
    ),
  ));
}