Saya memiliki ListView yang terdiri dari beberapa kartu Bagaimana saya bisa membuatnya sehingga ketika aplikasi dimulai, urutan kartu-kartu ini di ListView acak?

0
fasmof 5 April 2021, 17:21

2 jawaban

Jawaban Terbaik

Anda dapat meletakkan semua elemen Anda yang ingin Anda tampilkan dalam satu daftar (jika mereka belum ada dalam daftar) sebelum membuat kartu dan gunakan fungsi "shuffle":

https://api.flutter.dev/flutter/dart-core/list/shuffle.html.

1
Celt K. B. 5 April 2021, 14:35

Kartu acak.

Saya membangun contoh kerja penuh untuk Anda:

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,
              ),
            ),
          ),
        ],
      ),
    ],
  ),
);
0
Antonin GAVREL 5 April 2021, 14:54