【发布时间】:2021-04-05 14:21:34
【问题描述】:
我有一个由多个 Card 组成的 ListView,我怎样才能使它在应用程序启动时,这些 Card 在 ListView 中的顺序是随机的?
【问题讨论】:
-
显示更多代码以帮助您高效
标签: flutter random flutter-layout
我有一个由多个 Card 组成的 ListView,我怎样才能使它在应用程序启动时,这些 Card 在 ListView 中的顺序是随机的?
【问题讨论】:
标签: flutter random flutter-layout
您可以在生成卡片之前将所有要显示的元素放在一个列表中(如果它们尚未在列表中)并使用“洗牌”功能:
【讨论】:
我为您构建了一个完整的工作示例:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var imageNames = ["screen.png", "screen1.png", "screen2.png", "screen3.png", "screen4.png", "another_image.png"]; // you don't need to store the whole path
@override
void initState() {
imageNames.shuffle(); // shuffle your list of images
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: ListView(
padding: EdgeInsets.all(16),
children: [
for (String imageName in imageNames) // iterate over your list
buildImageCard('assets/images/$imageName'),
]
)));
}
}
Widget buildImageCard(String imagePath) => Card( // from https://stackoverflow.com/a/66893064/3161139
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
child: Column(
children: [
Stack(
children: [
Ink.image(
image: AssetImage(imagePath),
height: 240,
fit: BoxFit.cover,
),
Positioned(
bottom: 30,
right: 16,
left: 16,
child: Text(
'Interesting fact!',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 24,
),
),
),
],
),
],
),
);
【讨论】: