乐闻世界logo
搜索文章和话题

How to implement drop down list in flutter?

1个答案

1

To implement a dropdown list in Flutter, you typically use the DropdownButton or DropdownButtonFormField widgets. These widgets allow users to select a value from a dropdown menu. Below, I will provide a detailed explanation of the basic usage of these widgets and give a specific example of implementing a dropdown list.

Using DropdownButton

  1. Define the items for the dropdown list: First, define the items for the dropdown list as a list where each element corresponds to a DropdownMenuItem.

  2. Create the DropdownButton: Instantiate the DropdownButton widget and configure its properties to define its behavior and appearance.

  3. Manage the selected value: Implement a state variable to track the currently selected item.

Example Code

dart
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( home: DropdownExample(), ); } } class DropdownExample extends StatefulWidget { _DropdownExampleState createState() => _DropdownExampleState(); } class _DropdownExampleState extends State<DropdownExample> { String _selectedValue = 'One'; List<DropdownMenuItem<String>> get dropdownItems { List<DropdownMenuItem<String>> menuItems = [ DropdownMenuItem(child: Text("One"), value: "One"), DropdownMenuItem(child: Text("Two"), value: "Two"), DropdownMenuItem(child: Text("Three"), value: "Three"), ]; return menuItems; } Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('DropdownButton Example'), ), body: Center( child: DropdownButton( value: _selectedValue, onChanged: (String newValue) { setState(() { _selectedValue = newValue; }); }, items: dropdownItems, ), ), ); } }

Using DropdownButtonFormField

If you need to integrate the dropdown list into a form and require form validation, use DropdownButtonFormField. Its usage is similar to DropdownButton, but it functions as a form field.

Example Code

dart
DropdownButtonFormField( decoration: InputDecoration( labelText: "Select Number", ), value: _selectedValue, onChanged: (String newValue) { setState(() { _selectedValue = newValue; }); }, items: dropdownItems, validator: (value) { if (value == null) { return 'Please select a number'; } return null; }, )

Conclusion

By using Flutter's DropdownButton or DropdownButtonFormField, you can easily implement feature-rich dropdown lists in your application for various user input scenarios.

2024年7月1日 12:17 回复

你的答案