首页 > 解决方案 > Flutter:如何映射地图列表?

问题描述

我有一个非常简单的地图列表。

List<Map<String, String>> items = [
    { 'a': 'Some Text' },
    { 'b': 'Another Text' },
];

我想将上面的列表映射到下拉列表。

DropdownButton<String>(
  hint: Text('Select a value'),
  items: items.map((item) {
    return DropdownMenuItem<String>(
      value: // how to get key here a, b
      child: // how to get value 'Some Text', 'Another Text'
    );
  }).toList(),
  onChanged: (String newValue) {
    setState(() {
      // ...
    });
  },
 ),
)

如何获取地图的键,item 有属性keys但没有keyandvalues和 not value

标签: flutterdart

解决方案


您可以在下面复制粘贴运行完整代码
您需要使用DropdownButton<Map<String, String>>
您可以Text("${value.keys.first} ${value.values.first}")根据您的请求
代码段进行调整

DropdownButton<Map<String, String>>(
          value: dropdownValue,
          icon: Icon(Icons.arrow_downward),
          iconSize: 24,
          elevation: 16,
          style: TextStyle(color: Colors.deepPurple),
          underline: Container(
            height: 2,
            color: Colors.deepPurpleAccent,
          ),
          onChanged: (Map<String, String> newValue) {
            setState(() {
              dropdownValue = newValue;

              print(
                  "${dropdownValue.keys.first} ${dropdownValue.values.first}");
            });
          },
          items: items.map<DropdownMenuItem<Map<String, String>>>(
              (Map<String, String> value) {
            return DropdownMenuItem<Map<String, String>>(
              value: value,
              child: Text("${value.keys.first} ${value.values.first}"),
            );
          }).toList(),
        ),

工作演示

在此处输入图像描述

完整代码

import 'package:flutter/material.dart';

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> {
  List<Map<String, String>> items = [
    {'a': 'Some Text'},
    {'b': 'Another Text'},
  ];

  Map<String, String> dropdownValue;

  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            DropdownButton<Map<String, String>>(
              value: dropdownValue,
              icon: Icon(Icons.arrow_downward),
              iconSize: 24,
              elevation: 16,
              style: TextStyle(color: Colors.deepPurple),
              underline: Container(
                height: 2,
                color: Colors.deepPurpleAccent,
              ),
              onChanged: (Map<String, String> newValue) {
                setState(() {
                  dropdownValue = newValue;

                  print(
                      "${dropdownValue.keys.first} ${dropdownValue.values.first}");
                });
              },
              items: items.map<DropdownMenuItem<Map<String, String>>>(
                  (Map<String, String> value) {
                return DropdownMenuItem<Map<String, String>>(
                  value: value,
                  child: Text("${value.keys.first} ${value.values.first}"),
                );
              }).toList(),
            ),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

推荐阅读