dropdown_button.0.dart 1.7 KB
Newer Older
1 2 3 4
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
/// Flutter code sample for [DropdownButton].
6 7 8

import 'package:flutter/material.dart';

9
const List<String> list = <String>['One', 'Two', 'Three', 'Four'];
10

11
void main() => runApp(const DropdownButtonApp());
12

13
class DropdownButtonApp extends StatelessWidget {
14
  const DropdownButtonApp({super.key});
15 16 17 18 19

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
20
        appBar: AppBar(title: const Text('DropdownButton Sample')),
21
        body: const Center(
22
          child: DropdownButtonExample(),
23 24 25 26 27 28
        ),
      ),
    );
  }
}

29
class DropdownButtonExample extends StatefulWidget {
30
  const DropdownButtonExample({super.key});
31 32

  @override
33
  State<DropdownButtonExample> createState() => _DropdownButtonExampleState();
34 35
}

36 37
class _DropdownButtonExampleState extends State<DropdownButtonExample> {
  String dropdownValue = list.first;
38 39 40 41 42 43 44 45 46 47 48 49

  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
      value: dropdownValue,
      icon: const Icon(Icons.arrow_downward),
      elevation: 16,
      style: const TextStyle(color: Colors.deepPurple),
      underline: Container(
        height: 2,
        color: Colors.deepPurpleAccent,
      ),
50 51
      onChanged: (String? value) {
        // This is called when the user selects an item.
52
        setState(() {
53
          dropdownValue = value!;
54 55
        });
      },
56
      items: list.map<DropdownMenuItem<String>>((String value) {
57 58 59 60 61 62 63 64
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
  }
}