-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.

1
  • Please provide enough code so others can better understand or reproduce the problem. Commented Feb 21, 2022 at 12:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your time, i will change a few things and try it out and see what happens.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.