创建Flutter自定义Widget类出现空安全错误,我的修复方式是否正确?
修复方案合理性说明
你的修改方式可以解决当前编译报错,但不是符合空安全设计规范的最优方案。你将变量声明为可空类型(加?)后用!强行断言非空,相当于放弃了Dart空安全的编译期校验能力,如果后续调用OurImage组件时没有传入对应参数,运行时会直接触发空异常,存在线上崩溃隐患。
正确的声明方案
根据你的业务场景可以选择以下两种规范方案:
方案1:参数强制必传(推荐)
如果这三个参数是组件渲染必须的,给构造函数参数添加required修饰符,编译期会强制校验传参,从根源避免空值问题:
import 'package:flutter/material.dart'; class OurImage extends StatelessWidget { final String pathImage; final double widthImage; final double heightImage; const OurImage({ super.key, required this.pathImage, required this.heightImage, required this.widthImage, }); @override Widget build(BuildContext context) { final photo = Container( width: widthImage, height: heightImage, margin: const EdgeInsets.only(right: 20.0), decoration: BoxDecoration( image: DecorationImage( image: AssetImage(pathImage), fit: BoxFit.cover ) ), ); return photo; } }
方案2:设置默认值
如果参数允许不传,可以给参数配置非空默认值,未传参时自动使用默认值:
import 'package:flutter/material.dart'; class OurImage extends StatelessWidget { final String pathImage; final double widthImage; final double heightImage; const OurImage({ super.key, this.pathImage = 'assets/default_placeholder.png', this.heightImage = 100.0, this.widthImage = 100.0, }); @override Widget build(BuildContext context) { final photo = Container( width: widthImage, height: heightImage, margin: const EdgeInsets.only(right: 20.0), decoration: BoxDecoration( image: DecorationImage( image: AssetImage(pathImage), fit: BoxFit.cover ) ), ); return photo; } }
内容的提问来源于stack exchange,提问作者Diego Aaron
相关产品推荐
相关产品推荐

