如何修复!运算符返回空值问题

huangapple go评论63阅读模式
英文:

how to fix ! operator giving null value

问题

Null operator issue flutter

Flutter中的空操作问题

got an issue where the app crash because of null value but when i be using the app for a while then add this and hot reload the app it works

遇到了一个应用因为空值而崩溃的问题,但是当我使用应用一段时间后添加这个并热重载应用时,它可以正常工作

'${(controller.currentWeatherData.main!.temp! - 273.15).round().toString()}\u2103',
无法确定如何修复它

tried using ? but have another bug

尝试使用?但出现了另一个错误

Text(
  '${(controller.currentWeatherData.main!.temp! - 273.15).round().toString()}\u2103',
  //  'round',
  style: Theme.of(context)
      .textTheme
      .headline2!
      .copyWith(
          fontSize:
              AppDime.md_14,
          // color:
          //     Colors.black45,
          fontFamily:
              'flutterfonts'),
),
英文:

Null operator issue flutter

got an issue where the app crash because of null value but when i be using the app for a while then add this and hot reload the app it works

'${( controller.currentWeatherData.main!.temp! - 273.15).round().toString()}\u2103',

couldn't tell how to fix it

tried using ? but have another bug

Text(
  '${(controller.currentWeatherData.main!.temp! - 273.15).round().toString()}\u2103',
  //  'round',
  style: Theme.of(context)
      .textTheme
      .headline2!
      .copyWith(
          fontSize:
              AppDime.md_14,
          // color:
          //     Colors.black45,
          fontFamily:
              'flutterfonts'),
),

答案1

得分: 1

你可以首先进行空值检查,而不是使用空值断言,


if(controller.currentWeatherData.main?.temp!=null) 
   Text( '${( controller.currentWeatherData.main!.temp - 273.15).round().toString()}\u2103',)
 else Text("Got null"),

或者在情况下使用默认值

'${((controller.currentWeatherData.main?.temp?? 0) - 273.15).round().toString()}\u2103'
英文:

You can do a null check first instead of using null-assert,


if(controller.currentWeatherData.main?.temp!=null) 
   Text( '${( controller.currentWeatherData.main!.temp - 273.15).round().toString()}\u2103',)
 else Text("Got null"),

Or just default value on case can be

'${((controller.currentWeatherData.main?.temp?? 0) - 273.15).round().toString()}\u2103'

huangapple
  • 本文由 发表于 2023年5月21日 01:59:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76296655.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定