首页 > 解决方案 > 显示来自 tmdb 的流派

问题描述

我想显示所有类型,所以我在此处制作了 id 和名称的地图

class Genres {

  
Map<int , String > listOfGenres = {

28 : 'Action',
12 : 'Adventure',
16 : 'Animatiomn',
35 : 'Comedy',
80 : 'Crime' ,
99 : 'Documentary',
18 : 'Drama' ,
10751 : 'Family' ,
14 : 'Fantasy' ,
36 : 'History',
10402 : 'Music',
9648 : 'Mystery',
10749 : 'Romance' ,
878 : 'Science Fiction' ,
10770 : 'TV Movie' ,
53 : 'Thriller' ,
10752 : 'War',
37 : 'Western'
};


}

我想显示所有这些,并且某些电影的流派 ID 为 2,而其他电影的流派 ID 为 3 我尝试执行类似 for 循环的操作,但它只显示一个结果

Text(
                        Genres()
                            .listOfGenres[
                                results.genreIds[1]]
                            .toString(),
                      ),

标签: flutterdart

解决方案


您可以在下面复制粘贴运行完整代码
您可以使用Column和循环listOfGenres.keys
代码片段

Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        for (var element in Genres().listOfGenres.keys)
          Text(" ${element} ${Genres().listOfGenres[element]}")
      ],
    )

工作演示

在此处输入图像描述

完整代码

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class Genres {
  Map<int, String> listOfGenres = {
    28: 'Action',
    12: 'Adventure',
    16: 'Animatiomn',
    35: 'Comedy',
    80: 'Crime',
    99: 'Documentary',
    18: 'Drama',
    10751: 'Family',
    14: 'Fantasy',
    36: 'History',
    10402: 'Music',
    9648: 'Mystery',
    10749: 'Romance',
    878: 'Science Fiction',
    10770: 'TV Movie',
    53: 'Thriller',
    10752: 'War',
    37: 'Western'
  };
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            for (var element in Genres().listOfGenres.keys)
              Text(" ${element} ${Genres().listOfGenres[element]}")
          ],
        ),
      ),
    );
  }
}

推荐阅读