【问题标题】:A value of type 'TextSpan' can't be returned from the method 'build' because it has a return type of 'Widget'无法从方法“build”返回类型为“TextSpan”的值,因为它的返回类型为“Widget”
【发布时间】:2022-01-15 03:26:35
【问题描述】:

我需要创建一个自定义 SpanText,但我发现了这个问题。 无法从“build”方法返回“TextSpan”类型的值,因为它的返回类型为“Widget”。

代码是:

class StareWidget extends StatelessWidget {
  const StareWidget({Key? key, required this.text}) : super(key: key);
  final String text;
  @override
  Widget build(BuildContext context) {
    return TextSpan();
  }
}

【问题讨论】:

    标签: flutter widget


    【解决方案1】:

    根据documentation

    要在 Canvas 上绘制 TextSpan,请使用 TextPainter。要在小部件中显示文本跨度,请使用 RichText。对于具有单一样式的文本,请考虑使用 Text 小部件。

    所以你的TextSpan 需要有一个RichText 作为父级。

    【讨论】:

      【解决方案2】:

      试试下面的代码希望对你有帮助。

      参考 TextSpan here

      参考富文here

      class StareWidget extends StatelessWidget {
        const StareWidget({
          Key? key,
          required this.text,
        }) : super(key: key);
        final String text;
        @override
        Widget build(BuildContext context) {
          return Text.rich(
            TextSpan(
              text: 'This is textspan ',
              children: <InlineSpan>[
                TextSpan(
                  text: 'Widget in flutter',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
          );
        }
      }
      

      您的结果屏幕->

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-14
        • 1970-01-01
        • 2022-01-26
        • 1970-01-01
        • 1970-01-01
        • 2022-01-26
        • 2021-01-25
        相关资源
        最近更新 更多