首页 > 解决方案 > Flutter - 限制小部件以匹配其他小部件高度

问题描述

我想用照片创建列表项小部件,以及这张照片右侧的一些信息。由于网络图像可能太大,我还希望我的照片小部件的高度(同时保持纵横比)与“内容”小部件的高度相匹配,可能没有给出明确的高度。现在我的小部件看起来像这样:

物品

在 Android 中,我会限制图像大小: constraintTop_toTopOf(contentId) constraintBottom_toBottomOf(contentId)

是否可以在 Flutter 中做类似的事情?现在我的代码看起来像这样(我想避免在 ConstrainedBox 的 'maxHeight' 参数中给出明确的高度):

class SpeakerItemWidget extends StatelessWidget{

  final Speaker _speaker;

  SpeakerItemWidget(this._speaker);

  Widget _speakerItemContent() =>
      Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            '${_speaker.name} ${_speaker.surname}',
            style: TitleTextStyle(),
          ),
          SizedBox(height: Margin.small),
          Text(
            _speaker.title,
            style: DescriptionTextStyle(),
          ),
          Text(
            _speaker.company,
            style: DescriptionTextStyle(),
          )
        ],
      );

  @override
  Widget build(BuildContext context) =>
      InkWell(
        splashColor: Theme.of(context).accentColor,
        onTap: () => debugPrint('open event details'),
        child: Padding(
          padding: EdgeInsets.all(Margin.small),
          child: ConstrainedBox(
            constraints: BoxConstraints(
              maxHeight: 60,
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                FittedBox(
                  fit: BoxFit.contain,
                  child: SpeakerPhotoWidget(_speaker),
                ),
                _speakerItemContent(),
              ],
            ),
          ),
        ),
      );
}
class SpeakerPhotoWidget extends StatelessWidget{

  final Speaker _speaker;

  SpeakerPhotoWidget(this._speaker);

  @override
  Widget build(BuildContext context) {

    return  ConstrainedBox(
      constraints: BoxConstraints(
        //initial size of widget is 0,0 - causes crash when inside FittedBox
        minHeight: 1,
        minWidth: 1,
      ),
      child: Padding(
        padding: EdgeInsets.only(right: Margin.small),
        child: FadeInImage.assetNetwork(
          placeholder: 'assets/images/speaker_placeholder.png',
          image: 'some uri',
          fit: BoxFit.contain,
        ),
      )
    );
  }
}

标签: dartflutterflutter-layout

解决方案


推荐阅读