不能将 'double' 类型的值分配给类型为"int"的变量



我有一个SizedBox,我想在一定的限制下设置随机的高度和宽度大小。我为此编写了一个方法,其中我想将SizedBox的高度和宽度限制为屏幕的大小,但是当我通过屏幕大小来限制最大大小时,我得到了一个错误。如何将数据转换为正确工作?

@override
Widget build(BuildContext context) {


double randomHeight = MediaQuery.of(context).size.height;
double randomWidth = MediaQuery.of(context).size.width; 


Random random = new Random();

int min = 70;
int max = randomHeight;


int randomHeight = min + random.nextInt(max - min);



return Positioned(

height: randomHeight.toDouble(), 
child: SizedBox())}

这里有几种不同的方法可以将dart中的double类型转换为int类型。

double x = 2.5;
int a = x.toInt();
int b = x.truncate();
int c = x.round();
int d = x.ceil();
int e = x.floor();    
print(a); // 2
print(b); // 2
print(c); // 3
print(d); // 3
print(e); // 2

提供了一个链接,用于将此代码片段保存为多个片段。应用micro-repo。我是pieces团队的工程师,创建了这个功能:)https://mark.pieces.cloud/?p=d0e3418c1c

您的问题是您正在尝试分配int赋值给double输入变量来修复它:

将变量类型更改为double,并使用nextDouble()而不是nextInt()

double min = 70;
double max = randomHeight;
double randomHeight = min + random.nextDouble(max - min);

或者相反,将双精度类型转换为整型:

int min = 70;
int max = randomHeight.toInt();
int randomHeight = min + random.nextInt(max - min);

最新更新