首页 > 解决方案 > 错误:无法将元素类型“TextSpan”分配给列表类型“Widget”-Flutter

问题描述

我想优化我的代码,GridView因为我有 16 个 TextSpan 来对齐 4x4。问题是GridView 不接受 TextSpans。出现这个错误:The element type 'TextSpan' can't be assigned to the list type 'Widget'。我已经尝试删除,<Widget>但它没有工作。

这是代码:

child: GridView.count(
            primary: false,
            padding: const EdgeInsets.all(20),
            crossAxisSpacing: 10,
            mainAxisSpacing: 10,
            crossAxisCount: 4, // 4 tiles horizontally
            children: <Widget>[
              TextSpan(
                  text: widget.result + '  ',
                  style: TextStyle(
                    fontSize: 20.0,
                    fontWeight: FontWeight.bold,
                    color: checkdominantA(widget.predominant, widget.result),
                    height: 2.5,
                    letterSpacing: 0.7,
                  ),
                ),
                
                TextSpan(
                  text: widget.result2 + '  ',
                  style: TextStyle(
                    fontSize: 20.0,
                    fontWeight: FontWeight.bold,
                    color: checkdominantA(widget.predominant, widget.result2),
                    height: 2.5,
                    letterSpacing: 0.7,
                  ),
                ),
),
                //...

标签: androidflutterdartmobile

解决方案


Textspan 不是一个使用 RichText Widget 的小部件:

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

这会很好用;你的完整代码:

child: GridView.count(
          primary: false,
          padding: const EdgeInsets.all(20),
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
          crossAxisCount: 4,
          // 4 tiles horizontally
          children: <Widget>[
            RichText(
              text: TextSpan(
                text: widget.result + '  ',
                style: TextStyle(
                  fontSize: 20.0,
                  fontWeight: FontWeight.bold,
                  color: checkdominantA(widget.predominant, widget.result),
                  height: 2.5,
                  letterSpacing: 0.7,
                ),
              ),
            ),
            RichText(
              text: TextSpan(
                text: widget.result2 + '  ',
                style: TextStyle(
                  fontSize: 20.0,
                  fontWeight: FontWeight.bold,
                  color: checkdominantA(widget.predominant, widget.result2),
                  height: 2.5,
                  letterSpacing: 0.7,
                ),
              ),
            ),
          ],
        ),

推荐阅读