Flutter:GridView中大小不同的子项(所有子项都具有相同的最大大小)?

时间:2019-02-15 01:21:06

标签: android dart flutter

我正在学习Flutter / Dart,并且试图制作一个将Button Widget列表作为子级的GridView。按钮的大小应从一个到下一个变化。我唯一能找到的与此相关的东西是关于制作StaggeredGridView的问题,但是为了澄清我想要一个普通的网格视图,只是为了使按钮具有不同的整体大小,而网格单元格是最大大小。

我已经尝试过更改按钮的类型,在该容器内创建一个容器,并将按钮作为后者的子容器。似乎没有任何影响显示的按钮的最终大小。我还尝试过编辑直接构建的按钮的宽度和高度,而不是将带有按钮的容器放在其中。

Widget makeButton(B b){
  return new Container(
    width: 200.0,
    height: 200.0,
    child: Container(
      width: b.getSize(),
      height: b.getSize(),
      child: RaisedButton(
        color: Colors.red[50],
        child: Text(b.getText),
        onPressed: ((){...});
    )
 );
}

List<Widget> genButtons(int lSize){
  List<Widget> _list = new List<Widget>(lSize);
  for (int i = 0; i < lSize; i++){
    //new B(String text, double size) 
    _list[i] = makeButton(new B(i.toString(), (i+1)*50.0));
  }
  return _list;
 }

Widget buildGrid(int crossCount, double padding, double spacing){
    return new GridView.count(
      primary: true,
      padding: EdgeInsets.all(padding),
      crossAxisSpacing: spacing,
      crossAxisCount: crossCount,
      children: _myList,
    );
}

Widget build(BuildContext context) {
  return Scaffold(
      appBar: AppBar(
        title: Text('HELLO'),
      ),
      body: new Container(
        child: buildGrid(5, 10.0, 5.0, context),
        color: Colors.amber[100],
      )
  );
}

我的最终目标是使列表中创建的按钮在gridview的单元格内具有不同的大小。它们都可以具有相同的最大大小,即单元格本身的大小。如果可能,我想避免实现StaggeredGridView。

任何帮助都将不胜感激! :)

1 个答案:

答案 0 :(得分:0)

我认为问题出在:

Widget makeButton(B b){
  return new Container(
    width: 200.0,
    height: 200.0,
    child: Container(
      width: b.getSize(),
      height: b.getSize(),
      child: RaisedButton(
        color: Colors.red[50],
        child: Text(b.getText),
        onPressed: ((){...});
    )
 );
}

由于您已经制作了一个宽度和高度为200的容器,然后在其中放入另一个容器(大概是较小的尺寸),但是却从未告诉内部容器在其父容器中的位置,所以颤动会覆盖宽度和您为内部按钮指定的高度。

我假设要使它居中,所以用Center widget包裹内部容器。如果中心不是您想要的,请使用Align widget

另一个问题是,我不确定100%确定按钮小部件会自行调整其父级的尺寸。为此,您可以将RaisedButton放置在指定minWidth和height的ButtonTheme中,而不是使用容器。另一种选择是完全放弃按钮,而使用InkWell,因为这将为您提供“点击”效果,而没有尝试在其中显示文本等特定按钮的行为。