【问题标题】:Get the length of List that exists in Map<String,List<Object>> in Flutter获取 Flutter 中 Map<String,List<Object>> 中存在的 List 的长度
【发布时间】:2021-01-17 09:58:00
【问题描述】:

所以我正在制作具有这种结构的地图:

Map<String, List<Video>> mapName;

Video 只是一个具有 3 个属性的对象:String title、String videoURL、bool isDone。

我正计划创建一个 listView 来显示所有视频标题,所以我只是想弄清楚如何获取地图中存在的列表的长度。

我尝试了一些测试,它显示了这个:

print(videoList.values.map((list) => list.length));

    I/flutter (23887): (9)

现在确实我在列表中有 9 个视频,但我不能在我的列表视图 itemcount 中使用它,因为它需要一个 int 类型的数据。

【问题讨论】:

  • 你想用这个 print(videoList.values.map((list) => list.length));

标签: list flutter listview dart


【解决方案1】:

如果您的地图通过地图的键字符串有多个视频列表,您可以使用以下代码获取所有长度:

Map<String, List<Video>> mapName = {
  'video1': [Video(),Video()],
  'video2': [Video()],
  'video3': [Video(),Video(),Video()],
}; //Init

int total = 0;
  
mapName.keys.forEach((key){
  List<Video> video = mapName[key];
  int length = video.length;
  print('$key: $length');
  total += length;
});
  
print('total: $total');

颤振示例:

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class Video {
  final String name;
  final String url;
  final bool isDone;

  Video(this.name, this.url, this.isDone);
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Map<String, List<Video>> mapName = {
      'video1': [
        Video('Bunny', 'http://????', false),
        Video('Bunny10', 'http://????', true),
      ],
      'video2': [
        Video('Bunny2', 'http://????', false),
      ],
      'video3': [
        Video('BunnyX', 'http://????', false),
        Video('Bunny12', 'http://????', true),
        Video('BunnyZZ', 'http://????', false),
      ],
    }; //Init

    List<Video> mVideos = [];

    mapName.values.forEach((videos) {
      videos.forEach((video) {
        mVideos.add(video);
      });
    });

    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: ListView.builder(
          itemCount: mVideos.length,
          itemBuilder: (context, index) {
            Video video = mVideos[index];

            String name = video.name;
            String url = video.url;
            bool isDone = video.isDone;

            return ListTile(
              tileColor: isDone ? Colors.green : null,
              title: Text(name),
              subtitle: Text(url),
            );
          },
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text('Hello, World!', style: Theme.of(context).textTheme.headline4);
  }
}

【讨论】:

  • flutter中的例子在答案中
猜你喜欢
  • 2018-09-22
  • 1970-01-01
  • 1970-01-01
  • 2021-04-29
  • 2020-01-26
  • 1970-01-01
  • 2020-08-01
  • 2018-11-23
  • 1970-01-01
相关资源
最近更新 更多