How To Use Array Key Value Pair In Flutter Dropdown Button

admin_img Posted By Bajarangi soft , Posted On 03-11-2020

A collection of key/value pairs, from which you retrieve a value using its Modifying the map while iterating the keys or values may also break the iteration. Browse other questions tagged list flutter dart key-value or ask your own question. The Overflow Blog Podcast 264: Teaching yourself to code in prison .

How To Use Array Key Value Pair In Flutter Dropdown Button

Array Key Value Pair In Flutter Dropdown Button
Complete Code For Array Key Value Pair In Flutter Dropdown Button In Flutter
main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<KeyValueModel> _datas = [
    KeyValueModel(key: "Key 1", value: "Value 1"),
    KeyValueModel(key: "Key 2", value: "Value 2"),
    KeyValueModel(key: "Key 3", value: "Value 3"),
    KeyValueModel(key: "Key 4", value: "Value 4"),
    KeyValueModel(key: "Key 5", value: "Value 5"),
  ];

  String _selectedValue = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.orange[800],
        title: Text('Key value Pair - DropdownButton'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            DropdownButton<String>(
              items: _datas
                  .map((data) => DropdownMenuItem<String>(
                child: Text(data.key),
                value: data.value,
              ))
                  .toList(),
              onChanged: (String value) {
                setState(() => _selectedValue = value);
              },
              hint: Text('Select Key'),
            ),
            SizedBox(
              height: 25.0,
            ),
            Text(_selectedValue),
          ],
        ),
      ),
    );
  }
}

class KeyValueModel {
  String key;
  String value;

  KeyValueModel({this.key, this.value});
}

Related Post