Flutter运行报错type 'int' is not a subtype of type 'double'求解
问题根源
报错核心是Flutter中Positioned的left/top/height/width参数、Container的height/width参数都要求是double类型,你的代码存在两处类型不匹配问题:
- 调用
stack函数时传的尺寸参数都是int类型(比如80、111、447这些字面量),且stack函数的left/top/height/width参数没有指定类型默认是dynamic,如果你的createSize适配函数返回值是double,后续逻辑存在强转int的操作就会触发double不是int子类型的错误;如果createSize返回int,传给Positioned等需要double的参数就会触发int不是double子类型的错误。 createSize函数的入参没有明确类型约束,内部如果存在对入参的强制类型转换(比如as int/as double),也会触发类型不匹配报错。
修复方案
1. 明确所有参数类型,统一用double传递尺寸
给stack函数的所有参数加上明确类型,尺寸相关参数统一用double,传参时int字面量加.toDouble()或者直接写带.0的double值:
class H extends StatelessWidget { @override Widget build(BuildContext context) { return Container( // 传参时int转double child: stack(context, 'assets/sbg.png', 80.0, 111.0, 58.0, 215.0, 'assets/logo.png', 'title', 'subtitle'), ); } } // 所有参数明确指定类型,尺寸类参数用double Widget stack(BuildContext context, String image, double left, double top, double height, double width, String logo, String title, String subtitle){ return Stack( clipBehavior: Clip.none, children: [ Positioned( left: createSize(left, context), top: createSize(top, context), height: createSize(height, context), width: createSize(width, context), child: Column( children: [ Image.asset(logo), Text(title, style: TextStyle(),), Text(subtitle), ], ), ), Container( // 字面量直接写double类型 height: createSize(447.0, context), width: createSize(375.0, context), decoration: BoxDecoration( image: DecorationImage( image: AssetImage(image), fit: BoxFit.cover), ), ), ], ); }
2. 统一createSize函数的入参和返回值类型
确保createSize的入参是double,返回值也是double,内部避免无安全校验的强制类型转换,示例如下:
// 入参和返回值都明确为double double createSize(double size, BuildContext context) { // 你的适配逻辑,比如按屏幕宽度比例换算 final screenWidth = MediaQuery.of(context).size.width; return size * screenWidth / 375; }
如果适配逻辑必须要用到int类型的尺寸,转换时用安全的转换方法,比如double.tryParse()、toInt()/toDouble(),不要用as int/as double这种强转方式。
内容的提问来源于stack exchange,提问作者Abin Sunny
相关产品推荐
相关产品推荐

