1 | // Copyright 2014 The Flutter Authors. All rights reserved. |
2 | // Use of this source code is governed by a BSD-style license that can be |
3 | // found in the LICENSE file. |
4 | |
5 | import 'package:flutter/material.dart'; |
6 | |
7 | /// Flutter code sample for [DropdownButton.selectedItemBuilder]. |
8 | |
9 | Map<String, String> cities = <String, String>{ |
10 | 'New York' : 'NYC' , |
11 | 'Los Angeles' : 'LA' , |
12 | 'San Francisco' : 'SF' , |
13 | 'Chicago' : 'CH' , |
14 | 'Miami' : 'MI' , |
15 | }; |
16 | |
17 | void main() => runApp(const DropdownButtonApp()); |
18 | |
19 | class DropdownButtonApp extends StatelessWidget { |
20 | const DropdownButtonApp({super.key}); |
21 | |
22 | @override |
23 | Widget build(BuildContext context) { |
24 | return MaterialApp( |
25 | home: Scaffold( |
26 | appBar: AppBar(title: const Text('DropdownButton Sample' )), |
27 | body: const Center(child: DropdownButtonExample()), |
28 | ), |
29 | ); |
30 | } |
31 | } |
32 | |
33 | class DropdownButtonExample extends StatefulWidget { |
34 | const DropdownButtonExample({super.key}); |
35 | |
36 | @override |
37 | State<DropdownButtonExample> createState() => _DropdownButtonExampleState(); |
38 | } |
39 | |
40 | class _DropdownButtonExampleState extends State<DropdownButtonExample> { |
41 | String selectedItem = cities.keys.first; |
42 | |
43 | @override |
44 | Widget build(BuildContext context) { |
45 | return Center( |
46 | child: Row( |
47 | mainAxisAlignment: MainAxisAlignment.center, |
48 | children: <Widget>[ |
49 | Text('Select a city:' , style: Theme.of(context).textTheme.bodyLarge), |
50 | Padding( |
51 | padding: const EdgeInsets.symmetric(horizontal: 8.0), |
52 | child: DropdownButton<String>( |
53 | value: selectedItem, |
54 | onChanged: (String? value) { |
55 | // This is called when the user selects an item. |
56 | setState(() => selectedItem = value!); |
57 | }, |
58 | selectedItemBuilder: (BuildContext context) { |
59 | return cities.values.map<Widget>((String item) { |
60 | // This is the widget that will be shown when you select an item. |
61 | // Here custom text style, alignment and layout size can be applied |
62 | // to selected item string. |
63 | return Container( |
64 | alignment: Alignment.centerLeft, |
65 | constraints: const BoxConstraints(minWidth: 100), |
66 | child: Text( |
67 | item, |
68 | style: const TextStyle(color: Colors.blue, fontWeight: FontWeight.w600), |
69 | ), |
70 | ); |
71 | }).toList(); |
72 | }, |
73 | items: cities.keys.map<DropdownMenuItem<String>>((String item) { |
74 | return DropdownMenuItem<String>(value: item, child: Text(item)); |
75 | }).toList(), |
76 | ), |
77 | ), |
78 | ], |
79 | ), |
80 | ); |
81 | } |
82 | } |
83 | |