从flutter中的下拉列表返回多个值

fkvaft9z  于 2022-11-30  发布在  Flutter
关注(0)|答案(2)|浏览(147)

我有一个自定义的下拉按钮,当我从列表中选择一个值时,我想得到两个值。
这是自定义下拉按钮

Widget customJsonDropDown(List? jsonList, String? value, void onChange(val)) {
  return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(9),
        color: Colors.white,
      ),
      child: Padding(
          padding: const EdgeInsets.only(left: 10, right: 5),
          child: SizedBox(
              //width: 80,
              height: 50,
              child: DropdownButton<String>(
                hint: const Text('Select unit'),
                value: value,
                onChanged: (val) {
                  onChange(val);
                },
                items: jsonList?.map((item) {
                      return DropdownMenuItem(
                        value: item['conversion'].toString(),
                        child: Text(item['name']),
                      );
                    }).toList(),
                underline: Container(),
                isExpanded: true,
                
              ))));
              
}

这是Json列表

{
    "Length": [
        {
            "name": "Meter",
            "conversion": 1.0,
            "base_unit": true
        },
        {
            "name": "Millimeter",
            "conversion": 1000.0
        },
        {
            "name": "Centimeter",
            "conversion": 100.0
        }
    ]
}

正如你们所看到的,我从**['conversion']返回了一个String值,并使用jsonList中的['name']来显示名称。这样做很好,我得到了['conversion']值,但我更想要的是将Selected名称也存储在一个变量中。例如,如果我从下拉按钮中选择Meter**,它返回onChanged上的转换值,但我希望捕获选定的名称并将其分配给一个变量。
那么,我怎么能做到这一点,甚至是可能的吗?感谢任何帮助

huwehgph

huwehgph1#

试试这个:

import 'package:flutter/material.dart';

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

class Unit {
  final String name;
  final double conversion;
  final bool baseUnit;
  const Unit(
      {required this.name, required this.conversion, this.baseUnit = false});
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: SafeArea(
            child: Padding(
          padding: EdgeInsets.all(8.0),
          child: MyDropdown(),
        )),
      ),
    );
  }
}

class MyDropdown extends StatefulWidget {
  const MyDropdown({Key? key}) : super(key: key);

  @override
  State<MyDropdown> createState() => MyDropdownState();
}

class MyDropdownState extends State<MyDropdown> {
  Unit? _selected;

  final _units = const <Unit>[
    Unit(name: 'Meter', conversion: 1.0, baseUnit: true),
    Unit(name: 'Millimeter', conversion: 1000.0),
    Unit(name: 'Centimeter', conversion: 100)
  ];

  @override
  Widget build(BuildContext context) {
    return DropdownButton<Unit>(
        value: _selected,
        onChanged: (selected) => setState(() {
              debugPrint(
                  'Selected name: ${selected?.name}}, conversion: ${selected?.conversion}');
              _selected = selected;
            }),
        items: _units
            .map((Unit unit) => DropdownMenuItem<Unit>(
                  value: unit,
                  child: Text(unit.name),
                ))
            .toList());
  }
}
ki1q1bka

ki1q1bka2#

您可以为DropdownButton使用任何类型,而不仅仅是String。您也可以使用自己的模型类类型。
在本例中,由于值集是JSON格式的,因此使用<Map<String, dynamic>>作为DropdownButtonDropdownMenuItem的类型。这样,值将是选定项的Map,因此您可以轻松获得nameconversion
这是一个极简主义的例子,你可以尝试和调整它,以满足你的需要:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: SafeArea(
            child: Padding(
          padding: EdgeInsets.all(8.0),
          child: MyDropdown(),
        )),
      ),
    );
  }
}

class MyDropdown extends StatefulWidget {
  const MyDropdown({Key? key}) : super(key: key);

  @override
  State<MyDropdown> createState() => MyDropdownState();
}

class MyDropdownState extends State<MyDropdown> {
  Map<String, dynamic>? _selected;

  final _json = {
    'Length': [
      {'name': 'Meter', 'conversion': 1.0, 'base_unit': true},
      {'name': 'Millimeter', 'conversion': 1000.0},
      {'name': 'Centimeter', 'conversion': 100.0}
    ]
  };

  @override
  Widget build(BuildContext context) {
    return DropdownButton<Map<String, dynamic>>(
        value: _selected,
        onChanged: (selected) => setState(() {
              debugPrint(
                  'Selected name: ${selected?['name']}, conversion: ${selected?['conversion']}');
              _selected = selected;
            }),
        items: _json['Length']
            ?.map((Map<String, dynamic> item) =>
                DropdownMenuItem<Map<String, dynamic>>(
                  value: item,
                  child: Text(item['name']),
                ))
            .toList());
  }
}

相关问题