flutter - 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);
}
}
解决了!
解决方案
我认为图像列表中的问题,你没有用逗号分隔(,)
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 安全
推荐阅读
- apache-kafka - 如果其中一个代理不可用,Kafka 消费者将停止消费
- javascript - Javascript 弹出消息在使用 MasterPage 的 asp.net Web 应用程序中不起作用
- php - 如何从一个变量获取数据到另一个变量
- r - plot_ly 中的 z 参数到底是什么?
- c# - 如何在递归迭代对象子项时仅在找到特定值后添加数据
- javascript - 打开模式时出现奇怪的空格
- javascript - 如何解决未捕获的 TypeError:无法读取 null 的属性“addEventListener”?
- laravel - Laravel API 资源中的多级关系
- sql - 从表名在当前查询中的表中查询
- java - Java - 从函数返回 BigDecimal?