【问题标题】:Flutter: Different sized children (all with same max size) in GridView?颤振:GridView 中不同大小的孩子(都具有相同的最大尺寸)?
【发布时间】:2019-07-09 03:10:18
【问题描述】:

我正在学习 Flutter/Dart,我正在尝试制作一个 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。

非常感谢任何和所有帮助! :)

【问题讨论】:

  • 添加一些图像,你想要什么,

标签: android dart flutter


【解决方案1】:

我认为问题出在:

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 代替,因为这将为您提供“点击”效果,而不会尝试在其中显示文本等特定于按钮的行为。

【讨论】:

  • 抱歉,回复晚了,我刚刚能够使用 Center 小部件尝试您的解决方案,并且成功了! (我也将按钮更改为 FloatingActionButton )
猜你喜欢
  • 1970-01-01
  • 2021-04-20
  • 2021-05-04
  • 1970-01-01
  • 2011-10-02
  • 2015-03-02
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多