Flutter 空安全引发的一个bug

267 阅读1分钟

前言

今天新创建了一个flutter 项目,创建类时,声明了几个变量,但是在写构造器时出现了以下问题:

The parameter 'id' can't have a value of 'null' because of its type, but the implicit default value is 'null'. 

image.png

解决办法

网上搜了一下,没有找到答案,于是找了大佬问了下这个问题,终于找到了解决方案,在这我总结下

  • 非必填(属性至前加?)
  • 必填(构造器中加 required)
class ChatPage extends StatefulWidget {
  final String? title;
  final int? type;
  final String id;

  ChatPage({ required this.id,  this.title, required this.type});
  _Chat createState() => _Chat();
}