如何将带有列表视图的小部件限制为孩子的大小?

时间:2019-03-23 15:18:29

标签: flutter flutter-layout

我有这个SectorWidget,我的意思是它是分离的。

我将传递一个视图列表(具有相同的高度),但是我不想指定在ListView内或外部硬编码的高度。我希望它占据小部件的高度,就像Android中的wrap_content一样。但是我在搜索后尝试了很多方法(例如thisthis),但无法实现。在我的特定情况下,有没有办法做到这一点?

import 'package:flixapp/colors.dart';
import 'package:flutter/material.dart';

class SectorWidget extends StatelessWidget {
  final SectorViewModel viewModel;

  SectorWidget(this.viewModel);

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          width: MediaQuery.of(context).size.width,
          child: Material(
            color: Colors.transparent,
            child: InkWell(
              splashColor: kSplashColor,
              onTap: () {},
              child: Align(
                alignment: Alignment.centerLeft,
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  child: Text(
                    viewModel.title,
                    style: TextStyle(
                        fontWeight: FontWeight.w600,
                        color: Colors.black54,
                        fontSize: 30),
                  ),
                ),
              ),
            ),
          ),
          decoration: BoxDecoration(
              color: viewModel.titleBackgroundColor ?? Colors.amber),
        ),
        Container(
          color: Colors.red,
          child: ListView.builder(
            shrinkWrap: true,
            scrollDirection: Axis.horizontal,
            itemCount: viewModel.data?.length ?? 0,
            itemBuilder: (BuildContext context, int index) {
              var data = viewModel.data;
              if (data.isNotEmpty) return viewModel.data[index];
            },
          ),
        )
      ],
    );
  }
}

class SectorViewModel {
  String title;
  Color titleBackgroundColor;
  List<Widget> data;

  SectorViewModel({this.title, this.titleBackgroundColor, this.data});
}

1 个答案:

答案 0 :(得分:0)

当我对您的理解正确时,您希望根Column小部件与其子级的大小相匹配。为此,只需传入mainAxisSize: MainAxisSize.min(默认值为MainAxisSize.max-我也觉得有点烦,但是无论如何。)

还:子容器中不需要width: MediaQuery.of(context).size.width,。只需告诉父Column()使其子轴交叉crossAxisAlignment: CrossAxisAlignment.stretch