-2

I am trying to create a view that consist of a background image with widgets positioned dynamically in certain places on this image, each widget will have an x and y that needs to be calculated for different screens and for different image sizes.

what i did so far was showing the image in a stack and made a list of widgets where each widget type is being checked then create a flutter widget that corresponds with it adding it to this list and displaying it over the image in the stack, but i am looking for a cleaner way to create this behavior, also when rotating the screen the widgets are not being placed in a correct position,

Thank you for your time.

Oxodiya
  • 1
  • 1

1 Answers1

0

You can do something like:

Stack(
   children: [
     Image.asset('YOUR IMAGE HERE', fit: BoxFit.cover), // this is your bg image,
     ..List.generate(imagesCollection.length, (index) {
        
        // you could encapsulate all this logic in a separate widget

        var img = imagesCollection[index];
        var r = Random();
        
        // make sure to stay within the bounds of your screen
        var screenWidth = MediaQuery.of(context).size.width;
        var screenHeight = MediaQuery.of(context).size.height;

        var randomX = r.nextInt(screenWidth);
        var randomY = r.nextInt(screenHeight);

        // before you position the image, check that is within the bounds
        // check if the randomX - IMAGE_WITH is less than the screen width, same for the height
        return Positioned(
          top: randomY,
          left: randomX,
          child: Image.asset(img, width: IMAGE_WIDTH, height: IMAGE_HEIGHT)
        );
     }
   ]
)

Something around those lines.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Roman Jaquez
  • 2,499
  • 1
  • 14
  • 7