首页 > 解决方案 > Flutter 中的随机背景图像

问题描述

我正在使用 Flutter 2.5.2 版本。我想在每次打开颤振应用程序时显示随机背景图像。这是我的主要代码。我在显示背景时出错。

  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);
  }
}

解决了!

标签: flutterdartflutter-layout

解决方案


我认为图像列表中的问题,你没有用逗号分隔(,)

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'
  ];

这是完整的代码,它适用于我

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);
  }
}

注意:您只需要迁移 null 安全


推荐阅读