Home > Mobile >  How to put random photo in Flutter AssetImage?
How to put random photo in Flutter AssetImage?

Time:07-08

I have a code like this:

List backgrounds = ["bg.jpeg", "bg2.jpg", "bg3.jpg", "bg4.jpg", "bg5.jpg", "bg6.jpg", "bg7.jpg", "bg8.jpg", "bg9.jpg", "bg10.jpg", "bg11.jpg", "bg12.jpg"];
var randomBG;
randomBG = backgrounds[Random().nextInt(backgrounds.length)];
...
Container(
  decoration: const BoxDecoration(
    image: DecorationImage(
      image: AssetImage(
          randomBG.toString()),
      fit: BoxFit.fill,
    ),
  ),

But getting an error:

enter image description here

How can I solve this problem?

CodePudding user response:

BoxDecoration's image will get on runtime, therefor you cannot use const. Just remove const from BoxDecoration.

Container(
  decoration: BoxDecoration(
    image: DecorationImage(
      image: AssetImage(randomBG.toString()),
      fit: BoxFit.fill,
    ),
  ),
),
  • Related