Reputation: 133
I want display multiple Containers with images but I don't want fill the code with Containers, I want do some validations to displaying them. What is the best way to do this?
Container(
padding: EdgeInsets.all(10.0),
child:Image.asset("images/a.png"),//if validation ok show this1
),
Container(
padding: EdgeInsets.all(10.0),
child:Image.asset("images/b.png"),//if validation ok show this1
)
Container(
padding: EdgeInsets.all(10.0),
child:Image.asset("images/c.png"),//if validation ok show this1
)
//d.png e.png f.png g.png...
Im new at Dart, I just need a tip. Thanks!
Upvotes: 0
Views: 4946
Reputation: 3147
define ImageCard once
class ImageCard extends StatelessWidget {
final String imagePath;
ImageCard({this.imagePath});
@override
Widget build(BuildContext context) {
return imagePath != null // null handler
? Container(
padding: EdgeInsets.all(10.0),
child: Image.asset(imagePath),
)
: Container();
}
}
render multiple images programmatically at screen widget
List<Widget> renderImages(){
List<Widget> renderImages() {
var temp = <Widget>[];
for (var imagePath in imagePaths) {
// add some conditional logic here
// we only add more Item if it matches certain condition
if (imagePath.contains('3') || imagePath.contains('5')) {
temp.add(ImageCard(
imagePath: imagePath,
));
}
}
return temp;
}
}
@override
Widget build(BuildContext context){
...
child: Column(
children: renderImages(),
),
...
}
import 'package:flutter/material.dart';
List<String> imagePaths = [
"assets/images/flower-1.jpeg",
"assets/images/flower-2.jpeg",
"assets/images/flower-3.jpeg",
"assets/images/flower-4.jpeg",
"assets/images/flower-5.jpeg",
];
class ImageCardScreenEfficient extends StatelessWidget {
List<Widget> renderImages() {
var temp = <Widget>[];
for (var imagePath in imagePaths) {
// add some conditional logic here
if (imagePath.contains('3') || imagePath.contains('5')) {
temp.add(ImageCard(
imagePath: imagePath,
));
}
}
return temp;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Image Cards Efficient "),
),
body: SingleChildScrollView(
child: Center(
child: Column(
children: renderImages(),
),
),
),
);
}
}
class ImageCard extends StatelessWidget {
final String imagePath;
ImageCard({this.imagePath});
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(10.0),
child: Image.asset(imagePath),
);
}
}
You may look into this repo Github
Upvotes: 1
Reputation: 1343
you can create a function that returns a list of widgets
List<Widget> createWidget(bool isTrueValidation){
var images = ["images/a.png","images/b.png","images/c.png"];
List<Widget> list = List<Widget>();
for(var i in images){
list.add(
isTrueValidation ?
Container(
padding: EdgeInsets.all(10.0),
child:Image.asset(images[i])
) : Container()
);
}
}
Upvotes: 1