天天看點

flutter- 空安全: Try adding either an explicit non-‘null‘ default value or the ‘required‘ modifier.

空安全的報錯

一旦sdk更新到2.12以上之後,那麼就會執行空安全檢查,項目開始出現大面積報錯。

flutter- 空安全: Try adding either an explicit non-‘null‘ default value or the ‘required‘ modifier.

如圖所示: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- 空安全: Try adding either an explicit non-‘null‘ default value or the ‘required‘ modifier.

解決辦法

flutter降級?這當然是不可能的。

1. 傳參-空安全

  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 {
// ...

}
           
  1. 解決方法二,給參數提供預設值
void calculate({int factor = 42}) {
  // ...
  print(factor);
}
           
  1. 解決方法三,可選參數,也就是加問号 ?. 但是此方法有一個弊端, 問号表示允許為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;
}
           

------ 如果文章對你有用,感謝右上角 >>>點贊 | 收藏 <<<