我想用图像显示多个容器,但是我不想用容器填充代码,我想做一些验证以显示它们。做这个的最好方式是什么?
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...
我是Dart的新手,我只需要提示。谢谢!
答案 0 :(得分:1)
您可以创建一个返回小部件列表的函数
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()
);
}
}
答案 1 :(得分:1)
一次定义ImageCard
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();
}
}
在屏幕小部件上以编程方式渲染多张图像
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),
);
}
}
您可以查看此仓库Github