flutter - 我想每次添加不同的图像,我重复使用这张卡。如何在不复制粘贴整个代码的情况下做到这一点

标签 flutter flutter-layout flutter-web

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')
              ],
            ),
          )
        ],
      ),
    );

最佳答案

将图像 URL 传递给 OwnCard 类并显示它:

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]),
              ],
            ),
          )
        ],
      ),
    );

关于flutter - 我想每次添加不同的图像,我重复使用这张卡。如何在不复制粘贴整个代码的情况下做到这一点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69850934/

相关文章:

unit-testing - 单元测试失败,断言失败 : line 17: '<optimized out>' : is not true

Android Studio 在新的 Flutter 应用程序上出错

flutter - 当用户尝试放大屏幕时 flutter web 溢出

flutter - 在Dart _type错误中的模型类中解析数据?

flutter - 在单个 TextField 中为多行添加下划线 - Flutter/Dart

Flutter 'showDatePicker' 抛出异常 : Error: Expected a value of type 'String' , 但得到类型 'Null' 之一

Flutter 构建函数返回 null

flutter - 无法构建 build_runner :build_runner:Try using an explicit extension application of the wanted extension or hiding unwanted extensions from scope

flutter - 抛出另一个异常 : dependOnInheritedElement() was called before _PagesTestWidgetState. initState() 已完成

flutter - 如何为我的小部件添加边距?了解 EdgeInsets 的效果