Home > Mobile >  Random Background Image in Flutter
Random Background Image in Flutter

Time:10-14

I am using Flutter 2.5.2 version. I want to show random background image each time the flutter application were open. This is my main code. And I am having an error showing the background.

  class MainActivity extends StatelessWidget {
  final dynamic listBg = [
    'images/brand/bg_1.jpg',
        'images/brand/bg_2.jpg'
        'images/brand/bg_3.jpg'
        'images/brand/bg_4.jpg'
        'images/brand/bg_5.jpg'
  ];
  late final Random rnd;

  MainActivity({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MainBg(
      image: img(),
      child: const Scaffold(
        body: Center(
          child: Home(),
        ),
      ),
    );
  }

  AssetImage img() {
    int min = 0;
    int max = listBg.length - 1;
    rnd = Random();
    int r = min   rnd.nextInt(max - min);
    String imageName = listBg[r].toString();
    return AssetImage(imageName);
  }
}

Solved!

CodePudding user response:

I think the problem in the list of images, you didn't separate with a comma(,)

final dynamic listBg = [
    'images/brand/bg_1.jpg',
        'images/brand/bg_2.jpg',
        'images/brand/bg_3.jpg',
        'images/brand/bg_4.jpg',
        'images/brand/bg_5.jpg'
  ];

Here is the complete code and it works for me

class MainActivity extends StatelessWidget {
  final dynamic listBg = [
    'images/profile.png',
    'images/profile.png',
    'images/profile.png',
    'images/profile.png',


  ];
    Random rnd;

  MainActivity({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: img(),
            fit: BoxFit.cover,
          ),
        ),
        child: Container(),
      ),
    );
  }

  AssetImage img() {
    int min = 0;
    int max = listBg.length - 1;
    rnd = Random();
    int r = min   rnd.nextInt(max - min);
    String imageName = listBg[r].toString();
    return AssetImage(imageName);
  }
}

N.B: You just need to migrate null safe

  • Related