【问题标题】:How to use GridView to optimize my code? - Flutter如何使用 GridView 优化我的代码? - 颤振
【发布时间】:2021-11-25 01:52:44
【问题描述】:

我想使用GridView 组织此代码(我认为在这种情况下这是最好的选择),但我遇到了麻烦。我有 16 个 results 命名为 result1result2 ... result16,我想像 4x4 一样组织它,如下图所示:

下面是一小部分代码:

child: RichText(
            text: TextSpan(
              children: [
                TextSpan(
                  text: widget.result1 + '  ',
                  style: TextStyle(
                    fontSize: 20.0,
                    fontWeight: FontWeight.bold,
                    color: checkdominantA(widget.predominant, widget.result1),
                    height: 2.5,
                    letterSpacing: 0.7,
                  ),

                    // ...

                  TextSpan(
                  text: widget.result16 + '  ',
                  style: TextStyle(
                    fontSize: 20.0,
                    fontWeight: FontWeight.bold,
                    color: checkdominantA(widget.predominant, widget.result16),
                    height: 2.5,
                    letterSpacing: 0.7,
                  ),
                ),
                  
                ),
              ],
            ),
          ),

【问题讨论】:

    标签: android flutter dart mobile


    【解决方案1】:

    构建 Gridview 非常简单,只需按照本教程进行操作即可,GridView

    GridView.builder(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        mainAxisSpacing: 5.0,
        crossAxisSpacing: 5.0,
        crossAxisCount: 4,
        childAspectRatio: 1,
      ),
      itemCount: 16,
      itemBuilder: (BuildContext context, int index) {
        return Text(
                  '$index',
                  style: TextStyle(
                    fontSize: 20.0,
                    fontWeight: FontWeight.bold,
                    height: 2.5,
                    letterSpacing: 0.7,
                  );
      }
    ),
    

    【讨论】:

      【解决方案2】:

      根据GridViewdocumentation

      GridView.count(
        primary: false,
        padding: const EdgeInsets.all(20),
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
        crossAxisCount: 4,  // 4 tiles horizontally
        children: <Widget>[
          TextSpan(text: widget.result1 + '  '),
          TextSpan(text: widget.result2 + '  ')
          // ...
        ],
      )
      

      【讨论】:

      • 我收到此错误:The element type 'TextSpan' can't be assigned to the list type 'Widget'.
      【解决方案3】:

      根据GridView 文档: 添加这一行:

      crossAxisCount: 4,
      

      【讨论】:

        猜你喜欢
        • 2021-05-18
        • 2022-06-10
        • 1970-01-01
        • 2021-11-28
        • 2014-12-31
        • 2012-04-24
        • 1970-01-01
        • 1970-01-01
        • 2021-11-19
        相关资源
        最近更新 更多