Home > Blockchain >  A value of type 'double' can't be assigned to a variable of type 'int'
A value of type 'double' can't be assigned to a variable of type 'int'

Time:07-15

I have a SizedBox to which I want to set random height and width sizes with certain restrictions. I wrote a method for this, where I want to limit the height and width of the SizedBox to the size of the screen, but I get an error when I pass the screen size to limit the maximum size. How do I convert the data to work correctly ?

 @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())}

CodePudding user response:

Your problem is that you are trying to assign an int value to a double type variable, to fix it:

Change the variable types to double, and use nextDouble() instead of nextInt()

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

Or you can do the opposite by converting double types to int types:

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

CodePudding user response:

here is a couple different ways you can convert a double to an int in dart.

  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

heres a sharable link to this piece curated in what can be your very own Micro-repo for helpful snippets like this in @Pieces https://mark.pieces.cloud/?p=d0e3418c1c

  • Related