【问题标题】:Error: (The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't.) in Flutter错误:(参数类型“字符串?”无法分配给参数类型“字符串”,因为“字符串?”可以为空,而“字符串”不能。)在 Flutter 中
【发布时间】:2021-08-25 19:50:28
【问题描述】:

我是新来的,在传递字符串时遇到错误,到处查看,最后在 StackOverflow 中添加了这个

错误是

Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't.

void errorSnackBar(BuildContext context, String? text) {
  ScaffoldMessenger.of(context).showSnackBar(new SnackBar(
    duration: new Duration(seconds: 4),
    content: new Row(
      children: <Widget>[
        Icon(
          Icons.error,
          color: Colors.red,
        ),
        Padding(
          padding: const EdgeInsets.fromLTRB(10.0, 0, 0, 0),
          child: new Text(text),
        ),
      ],
    ),
  ));
}

【问题讨论】:

标签: flutter android-studio dart visual-studio-code flutter-layout


【解决方案1】:

我遇到了同样的问题

就我而言,我不得不使用 null 安全性。

final String? name

我必须使用 ! 标记才能使其工作。比如:如果我想调用它

index.name!

【讨论】:

    【解决方案2】:

    使用 .toString() 将文本转换为字符串

     void errorSnackBar(BuildContext context, String? text) {
          ScaffoldMessenger.of(context).showSnackBar(new SnackBar(
            duration: new Duration(seconds: 4),
            content: new Row(
              children: <Widget>[
                Icon(
                  Icons.error,
                  color: Colors.red,
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(10.0, 0, 0, 0),
                  child: new Text(text.toString()),
                ),
              ],
            ),
          ));
        }
    

    【讨论】:

      【解决方案3】:

      这可能对新手有所帮助, 我有类似的问题,我解决它的方式

       Padding(
            padding: const EdgeInsets.fromLTRB(10.0, 0, 0, 0),
            child: new Text(text ?? 'Default Value'),
          ),
      

      请参阅此Link 了解更多信息

      【讨论】:

        【解决方案4】:

        Text() 需要String 作为其第一个参数(即不是null)。 null 不是 String 类型的有效值,就像 123 不是 String 类型的有效值一样。

        如果您的错误消息是String?,您需要处理它是null 的情况,然后才能将其传递给Text()。一些选项是:

        1. 检查是否为null并提前返回:
        void errorSnackBar(BuildContext context, String? text) {
          if (text == null) return;
          // dart uses "type promotion" to know that text is definitely not null here
          final textWidget = Text(text);  // this is fine
          ScaffoldMessenger.of(context) ... // show snackbar
        }
        
        1. 如果您知道只有在text 为非空时才调用errorSnackBar,请尝试更改其类型:
        void errorSnackBar(BuildContext context, String text) {
          // rest of the method the same
        }
        

        【讨论】:

        • 谢谢你的回复。if (text == null) return;最终文本小部件 = 文本(文本);为我工作我无法猜到那个字符串? text 在 Text 中存储 null
        猜你喜欢
        • 1970-01-01
        • 2021-09-04
        • 1970-01-01
        • 2021-12-20
        • 2021-09-20
        • 2021-10-21
        • 2021-10-13
        • 1970-01-01
        相关资源
        最近更新 更多