You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter:无法将String?赋值给String参数的错误求助

解决Flutter空安全错误:'String?'无法赋值给'String'

错误提示'The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't'是Dart空安全机制的约束导致的——Text组件的data参数要求传入非空字符串,但你的代码中两处可空值直接传递给了这个参数。

分步解决:

1. 修正Quote类的属性可空性

因为你创建Quote实例时用了required关键字,说明text和author一定有值,没必要设为可空类型。修改quote.dart:

class Quote {
  String text; // 移除?,改为非空字符串
  String author;

  Quote({required this.text, required this.author});
}

2. 修正QuoteCard的参数可空性

你在调用QuoteCard时,传入的都是列表中已初始化的Quote实例,不存在空值,所以可以把QuoteCard的quote参数改为非空,并添加required修饰:

class QuoteCard extends StatelessWidget {
  final Quote quote; // 移除?
  const QuoteCard({super.key, required this.quote}); // 添加required

  @override
  Widget build(BuildContext context) {
    return Card(
        margin: const EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 0),
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Text(
                quote.text, // 现在text是非空值,符合参数要求
                style: const TextStyle(
                  letterSpacing: 2.0,
                  fontSize: 18.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 6.0,),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Text(
                    quote.author, // author同样是非空值
                    style: const TextStyle(
                      letterSpacing: 2.0,
                      fontSize: 14.0,
                      fontFamily: 'FiraSans',
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      );
  }
}

不推荐的临时方案(存在崩溃风险)

如果暂时不想修改类结构,也可以用空断言运算符!强制告诉编译器值非空,但如果后续代码中出现空值会直接崩溃:

Text(quote!.text!)

内容的提问来源于stack exchange,提问作者Ahmed Maged

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 19:10:29