【问题标题】:Flutter - Compare two listsFlutter - 比较两个列表
【发布时间】:2021-04-15 01:24:49
【问题描述】:

我正在尝试比较两个列表以显示图像,具体取决于其结果。

基本思想是显示图片列表(降低不透明度),当一个元素同时包含在两个列表中时,显示图片不透明度。

在两个列表中使用print() 时,我得到以下结果:

s:      [Aquatic, Desert, Grassland, Temperate, Tigra, Tropical, Tundra]
biomes: [Grassland, Tropical]

所以想法是,只有草地和热带(在这个例子中)得到充分展示,而其他保持半透明。

不幸的是,所有图片都是半透明的,我不太确定我错过了什么。

Widget BiomeElement(List<String> s, biomes) {

  List<Widget> list = new List<Widget>();
    for (var i = 0; i < s.length; i++) {
      list.add(
        Padding(
          padding: const EdgeInsets.all(4.0),
          child: new Opacity(
            opacity: (s.contains(biomes) ? 1 : 0.3),
            child: Column(
              children: [
                Image.asset(
                  'assets/biomes/biome_' + s[i].toLowerCase() + '.png',
                  height: 35,
                  width: 35),
              ],
            ),
          ),
        ),
      );
    }

   return new Row(
      // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: list
   );
}

【问题讨论】:

  • 使用上面提供的代码得到什么结果?
  • 所有生物群系都被列出,但匹配不起作用。它们保持半透明

标签: flutter


【解决方案1】:

希望对你有帮助,先转换成对象列表

final s = ["Aquatic", "Desert", "Grassland", "Temperate", "Tigra", "Tropical", "Tundra"];
final biomes = ["Grassland", "Tropical"];

final hasil = s.map((e) => {"name": e, "opacity": biomes.contains(e)}).toList();
print(hasil);

结果是这样的:

[
 {name: Aquatic, opacity: false}, 
 {name: Desert, opacity: false}, 
 {name: Grassland, opacity: true}, 
 {name: Temperate, opacity: false}, 
 {name: Tigra, opacity: false}, 
 {name: Tropical, opacity: true}, 
 {name: Tundra, opacity: false}
]

适合你的情况

Widget BiomeElement(List<String> hasil) {

  List<Widget> list = new List<Widget>();
    for (var i = 0; i < hasil.length; i++) {
      list.add(
        Padding(
          padding: const EdgeInsets.all(4.0),
          child: new Opacity(
            opacity: hasil[i]['opacity']? 1 : 0.3), // true for 1 and false for 0.3
            child: Column(
              children: [
                Image.asset(
                  'assets/biomes/biome_' + hasil[i]['name'].toLowerCase() + '.png',
                  height: 35,
                  width: 35),
              ],
            ),
          ),
        ),
      );
    }

   return new Row(
      // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: list
   );
}

【讨论】:

    【解决方案2】:

    您需要更改检查匹配的方式。

    从您的控制台结果来看,biomes 是一个列表,您将其传递给 .contains 方法,该方法接受一个对象而不是对象列表。

    所以这个检查,s.contains(biomes) 不起作用。如果您在 BiomeElement 方法中为 biomes 分配了一个类型,您就会检测到它。

    解决方案: 由于您正在迭代s,因此您可以检查当前索引处的s 元素是否包含在biomes 列表中,如下所示:

    biomes.contains(s[i])
    

    【讨论】:

      猜你喜欢
      • 2011-06-19
      • 2011-02-15
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多