Home > Back-end >  I want to add different images each time, I reuses this Card.How to do that without copy pasting the
I want to add different images each time, I reuses this Card.How to do that without copy pasting the

Time:11-05

class OwnCard extends StatelessWidget {
  const OwnCard({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Column(
        children: [
          AspectRatio(
            aspectRatio: 18 / 11,
            child: Image.asset('assets/diamond.png'),
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(16, 12, 16, 8),
            child: Column(
              children: [
                Text('Title'),
                SizedBox(
                  height: 12,
                ),
                Text('Secondary Text')
              ],
            ),
          )
        ],
      ),
    );

CodePudding user response:

pass image url to OwnCard class and display it:

List<String> urls = ['', '', ''];

GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        childAspectRatio: 1.0,
      ),
      itemCount: 12,
      itemBuilder: (context, index) {
        return OwnCard(urls: urls);
      },
    );
    
class OwnCard extends StatelessWidget {
  final List<String> urls;

  const OwnCard({
    Key? key,
    required this.urls,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Column(
        children: [
          AspectRatio(
            aspectRatio: 18 / 11,
            child: Image.network(urls[0]),
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(16, 12, 16, 8),
            child: Column(
              children: [
                Text('Title'),
                SizedBox(
                  height: 12,
                ),
                Text('Secondary Text'),
                Image.network(urls[1]),
                Image.network(urls[2]),
              ],
            ),
          )
        ],
      ),
    );

CodePudding user response:

I prefer this way


class OwnCard extends StatelessWidget {
  final String imagePath;
  final String title;
  final String secondaryText;

  const OwnCard(
      {Key? key,
      required this.imagePath,
      required this.title,
      required this.secondaryText})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Column(
        children: [
          AspectRatio(
            aspectRatio: 18 / 11,
            child: Image.asset(imagePath),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
            child: Column(
              children: [
                Text(title),
                const SizedBox(
                  height: 12,
                ),
                Text(secondaryText)
              ],
            ),
          )
        ],
      ),
    );
  }
}


  • Related