空安全的报错
一旦sdk升级到2.12以上之后,那么就会执行空安全检查,项目开始出现大面积报错。
如图所示:The parameter ‘isDart’ can’t have a value of ‘null’ because of its type, but the implicit default value is ‘null’.
Try adding either an explicit non-‘null’ default value or the ‘required’ modifier.
解决办法
flutter降级?这当然是不可能的。
1. 传参-空安全
- 解决方法一,添加关键字
required
。缺点:调用类 BottomBarView 时,每个参数必传
class BottomBarView extends StatefulWidget {
BottomBarView({Key? key, required this.tabIconsList, required this.changeIndex, required this.addClick}) : super(key: key);
final Function(int index) changeIndex;
final Function addClick;
final List<TabIconData> tabIconsList;
@override
_BottomBarViewState createState() => _BottomBarViewState();
}
class _BottomBarViewState extends State<BottomBarView> with TickerProviderStateMixin {
// ...
}
- 解决方法二,给参数提供默认值
void calculate({int factor = 42}) {
// ...
print(factor);
}
- 解决方法三,可选参数,也就是加问号 ?. 但是此方法有一个弊端, 问号表示允许为null,后续调用该参数时,所有用到的地方都得加感叹号(断言符号)用于先判断该参数是否为空. 赋值时,需要使用双问号以防止其值是null时给其一个默认值
class Foo extends StatelessWidget {
const Foo({Key? key, User? user, int? count});// Key后加一个问号
print(user!.name);
print(user!.age);
int totalCount = count ?? 0;
print(count??0);
}
2.初始化-空安全
空安全模式下,要求
所有对象在申明的时候就必须要初始化
.
比如 dart < 2.12 之前的版本可以这样
class HttpServiceImpl implements HttpService {
static HttpServiceImpl instance; // 1.申明对象
instance = HttpServiceImpl(); // 2.对象进行初始化
HttpServiceImpl();
}
一. 空安全版本必须将1,2 这两步骤合并
class HttpServiceImpl implements HttpService {
static HttpServiceImpl instance = HttpServiceImpl(); // 申明并且初始化
HttpServiceImpl();
}
二. 有一些特殊的类,无法初始化,可以使用关键字
late
(延迟初始化)
class ActivesView extends StatefulWidget {
ActivesView({Key? key}) : super(key: key);
@override
_ActivesViewState createState() => _ActivesViewState();
}
class _ActivesViewState extends State<ActivesView> {
late ScrollController scrollController; // 1.申明对象 2 通过关键字 late 延迟初始化
late AnimationController controller;
late Animation<double> animation;
}
------ 如果文章对你有用,感谢右上角 >>>点赞 | 收藏 <<<