Flutter下拉选择插件awesome_dropdown的使用

Flutter下拉选择插件awesome_dropdown的使用

Awesome DropDown

一个可定制的下拉库,处理所有触摸和点击事件,包括iOS和移动返回按钮回调。

安装

pubspec.yaml文件中添加以下依赖项。并在你的文件中导入它。

dependencies:
  awesome_dropdown:^0.0.4
import 'package:awesome_dropdown/awesome_dropdown.dart';

快速开始

AwesomeDropdown添加到小部件树中:

AwesomeDropDown(
  isPanDown: _isPanDown,
  dropDownList: _list,
  dropDownIcon: Icon(Icons.arrow_drop_down, color: Colors.grey, size: 23,),
  selectedItem: _selectedItem,
  onDropDownItemClick: (selectedItem) {
    _selectedItem = selectedItem;
  },
  dropStateChanged: (isOpened) {
    _isDropDownOpened = isOpened;
    if (!isOpened) {
      _isBackPressedOrTouchedOutSide = false; 
    }
  },
)

自定义主体

AwesomeDropDown(
  isPanDown: _isPanDown,
  isBackPressedOrTouchedOutSide: _isBackPressedOrTouchedOutSide,
  dropDownBGColor: Colors.white,
  dropDownOverlayBGColor: Colors.transparent,
  padding: 8,
  dropDownIcon: Icon(Icons.arrow_drop_down, color: Colors.grey, size: 23,),
  elevation: 5,
  dropDownBorderRadius: 10,
  dropDownTopBorderRadius: 50,
  dropDownBottomBorderRadius: 50,
  dropDownIconBGColor: Colors.transparent,
  dropDownList: _list,
  selectedItem: _selectedItem,
  numOfListItemToShow: 4,
  selectedItemTextStyle: TextStyle(
    color: Colors.black,
    fontSize: 16,
    fontWeight: FontWeight.normal
  ),
  dropDownListTextStyle: TextStyle(
    color: Colors.grey,
    fontSize: 15,
    backgroundColor: Colors.transparent
  ),
  onDropDownItemClick: (selectedItem) {
    _selectedItem = selectedItem;
  },
  dropStateChanged: (isOpened) {
    _isDropDownOpened = isOpened;
    if (!isOpened) {
      _isBackPressedOrTouchedOutSide = false;
    }
  },
)

示例代码

示例 1

import 'package:flutter/material.dart';
import 'package:awesome_dropdown/awesome_dropdown.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Awesome DropDown Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SimpleDropDown(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class SimpleDropDown extends StatefulWidget {
  [@override](/user/override)
  _SimpleDropDownState createState() => _SimpleDropDownState();
}

class _SimpleDropDownState extends State<SimpleDropDown> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Awesome DropDown"),
      ),
      body: AwesomeDropDown(
        dropDownList: ["Abc", "DEF", "GHI", "JKL", "MNO", "PQR"],
      ),
    );
  }
}

示例 2

class DropDownWithPanDownAndDrawer extends StatefulWidget {
  [@override](/user/override)
  _DropDownWithPanDownAndDrawerState createState() => _DropDownWithPanDownAndDrawerState();
}

class _DropDownWithPanDownAndDrawerState extends State<DropDownWithPanDownAndDrawer> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  bool _isBackPressedOrTouchedOutSide = false,
      _isDropDownOpened = false,
      _isPanDown = false;
  late List<String> _list;
  String _selectedItem = '';

  [@override](/user/override)
  void initState() {
    _list = ["Abc", "DEF", "GHI", "JKL", "MNO", "PQR"];
    _selectedItem = 'Select Item';
    super.initState();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _removeFocus,
      onPanDown: (focus) {
        _isPanDown = true;
        _removeFocus();
      },
      child: Scaffold(
        backgroundColor: Colors.white,
        key: _scaffoldKey,
        endDrawer: Drawer(
          child: ListView(
            padding: EdgeInsets.zero,
            children: <Widget>[
              DrawerHeader(
                child: Text('Drawer Header'),
                decoration: BoxDecoration(
                  color: Colors.blue,
                ),
              ),
              ListTile(
                title: Text('Item 1'),
                onTap: () {},
              ),
              ListTile(
                title: Text('Item 2'),
                onTap: () {},
              ),
            ],
          ),
        ),
        appBar: PreferredSize(
          preferredSize: AppBar().preferredSize,
          child: SafeArea(
            child: PreferredSize(
                preferredSize: Size.fromHeight(100.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      margin: EdgeInsets.only(left: 60),
                      child: Text('Awesome DropDown',
                          style: TextStyle(
                              color: Colors.black,
                              fontSize: 22,
                              fontWeight: FontWeight.bold)),
                    ),
                    Container(
                        margin: EdgeInsets.only(right: 8),
                        child: IconButton(
                            icon: Icon(
                              Icons.menu,
                              size: 30,
                              color: Colors.blueAccent,
                            ),
                            onPressed: () {
                              _onDrawerBtnPressed();
                            }))
                  ],
                )),
          ),
        ),
        body: Container(
          width: MediaQuery.of(context).size.width,
          margin: EdgeInsets.only(top: 15, left: 16, right: 20),
          child: AwesomeDropDown(
            isPanDown: _isPanDown,
            dropDownList: _list,
            isBackPressedOrTouchedOutSide: _isBackPressedOrTouchedOutSide,
            selectedItem: _selectedItem,
            onDropDownItemClick: (selectedItem) {
              _selectedItem = selectedItem;
            },
            dropStateChanged: (isOpened) {
              _isDropDownOpened = isOpened;
              if (!isOpened) {
                _isBackPressedOrTouchedOutSide = false;
              }
            },
          ),
        ),
      ),
    );
  }

  void _removeFocus() {
    if (_isDropDownOpened) {
      setState(() {
        _isBackPressedOrTouchedOutSide = true;
      });
    }
  }

  void _onDrawerBtnPressed() {
    if (_isDropDownOpened) {
      setState(() {
        _isBackPressedOrTouchedOutSide = true;
      });
    } else {
      _scaffoldKey.currentState!.openEndDrawer();
      FocusScope.of(context).requestFocus(FocusNode());
    }
  }
}

示例 3

class DropDownWithiOsBackIcon extends StatefulWidget {
  [@override](/user/override)
  _DropDownWithiOsBackIconState createState() => _DropDownWithiOsBackIconState();
}

class _DropDownWithiOsBackIconState extends State<DropDownWithiOsBackIcon> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  bool _isBackPressedOrTouchedOutSide = false,
      _isDropDownOpened = false,
      _isPanDown = false,
      _navigateToPreviousScreenOnIOSBackPress = true;
  late List<String> _list;
  String _selectedItem = '';

  [@override](/user/override)
  void initState() {
    _list = ["Abc", "DEF", "GHI", "JKL", "MNO", "PQR"];
    _selectedItem = 'Select Item';
    super.initState();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _removeFocus,
      onPanDown: (focus) {
        _isPanDown = true;
        _removeFocus();
      },
      child: Scaffold(
        backgroundColor: Colors.white,
        key: _scaffoldKey,
        appBar: PreferredSize(
          preferredSize: AppBar().preferredSize,
          child: SafeArea(
            child: PreferredSize(
                preferredSize: Size.fromHeight(100.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    SizedBox(
                      width: 30,
                      child: Container(
                          margin: EdgeInsets.only(
                            left: 8,
                          ),
                          child: IconButton(
                            color: Colors.black,
                            icon: Icon(
                              Icons.arrow_back_ios,
                            ),
                            onPressed: _onWillPop,
                          )),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                        right: 60,
                      ),
                      child: Text('Awesome DropDown',
                          style: TextStyle(
                              color: Colors.black,
                              fontSize: 22,
                              fontWeight: FontWeight.bold)),
                    ),
                  ],
                )),
          ),
        ),
        body: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: MediaQuery.of(context).size.width,
              margin: EdgeInsets.only(top: 15, left: 16, right: 20),
              child: AwesomeDropDown(
                isPanDown: _isPanDown,
                dropDownList: _list,
                isBackPressedOrTouchedOutSide: _isBackPressedOrTouchedOutSide,
                selectedItem: _selectedItem,
                onDropDownItemClick: (selectedItem) {
                  _selectedItem = selectedItem;
                },
                dropStateChanged: (isOpened) {
                  _isDropDownOpened = isOpened;
                  if (!isOpened) {
                    _isBackPressedOrTouchedOutSide = false;
                  }
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _removeFocus() {
    if (_isDropDownOpened) {
      setState(() {
        _isBackPressedOrTouchedOutSide = true;
      });
      _navigateToPreviousScreenOnIOSBackPress = false;
    }
  }

  Future<bool> _onWillPop() {
    if (_scaffoldKey.currentState!.isEndDrawerOpen) {
      Navigator.of(context).pop();
      return Future.value(false);
    } else {
      if (_isDropDownOpened) {
        setState(() {
          _isBackPressedOrTouchedOutSide = true;
        });
        FocusManager.instance.primaryFocus!.unfocus();
        return Future.value(false);
      } else {
        if (_navigateToPreviousScreenOnIOSBackPress) {
          Navigator.of(context).pop();
          return Future.value(true);
        } else {
          _navigateToPreviousScreenOnIOSBackPress = true;
          return Future.value(false);
        }
      }
    }
  }
}

示例 4

class FullyFunctionalAwesomeDropDown extends StatefulWidget {
  [@override](/user/override)
  _FullyFunctionalAwesomeDropDownState createState() => _FullyFunctionalAwesomeDropDownState();
}

class _FullyFunctionalAwesomeDropDownState extends State<FullyFunctionalAwesomeDropDown> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  bool _isBackPressedOrTouchedOutSide = false,
      _isDropDownOpened = false,
      _isPanDown = false,
      _navigateToPreviousScreenOnIOSBackPress = true;
  late List<String> _list;
  String _selectedItem = 'Select Country';

  [@override](/user/override)
  void initState() {
    _list = ["Abc", "DEF", "GHI", "JKL", "MNO", "PQR"];
    super.initState();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: _onWillPop,
        child: GestureDetector(
          onTap: _removeFocus,
          onPanDown: (focus) {
            _isPanDown = true;
            _removeFocus();
          },
          child: Scaffold(
            backgroundColor: Colors.white,
            key: _scaffoldKey,
            endDrawer: Drawer(
              child: ListView(
                padding: EdgeInsets.zero,
                children: <Widget>[
                  DrawerHeader(
                    child: Text('Drawer Header'),
                    decoration: BoxDecoration(
                      color: Colors.blue,
                    ),
                  ),
                  ListTile(
                    title: Text('Item 1'),
                    onTap: () {},
                  ),
                  ListTile(
                    title: Text('Item 2'),
                    onTap: () {},
                  ),
                ],
              ),
            ),
            appBar: PreferredSize(
              preferredSize: AppBar().preferredSize,
              child: SafeArea(
                child: PreferredSize(
                    preferredSize: Size.fromHeight(100.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        SizedBox(
                          width: 30,
                          child: Container(
                              margin: EdgeInsets.only(
                                left: 8,
                              ),
                              child: IconButton(
                                color: Colors.black,
                                icon: Icon(
                                  Icons.arrow_back_ios,
                                ),
                                onPressed: _onWillPop,
                              )),
                        ),
                        Text('Awesome DropDown',
                            style: TextStyle(
                                color: Colors.black,
                                fontSize: 22,
                                fontWeight: FontWeight.bold)),
                        Container(
                          child: Padding(
                              padding: EdgeInsets.only(right: 8),
                              child: IconButton(
                                  icon: Icon(
                                    Icons.menu,
                                    size: 30,
                                    color: Colors.blueAccent,
                                  ),
                                  onPressed: () {
                                    _onDrawerBtnPressed();
                                  }))
                        )
                      ],
                    )),
              ),
            ),
            body: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  width: MediaQuery.of(context).size.width,
                  margin: EdgeInsets.only(top: 15, left: 16, right: 20),
                  child: AwesomeDropDown(
                    isPanDown: _isPanDown,
                    isBackPressedOrTouchedOutSide: _isBackPressedOrTouchedOutSide,
                    padding: 8,
                    dropDownIcon: Icon(
                      Icons.arrow_drop_down,
                      color: Colors.grey,
                      size: 23,
                    ),
                    elevation: 5,
                    dropDownBorderRadius: 10,
                    dropDownTopBorderRadius: 50,
                    dropDownBottomBorderRadius: 50,
                    dropDownIconBGColor: Colors.transparent,
                    dropDownOverlayBGColor: Colors.transparent,
                    dropDownBGColor: Colors.white,
                    dropDownList: _list,
                    selectedItem: _selectedItem,
                    numOfListItemToShow: 4,
                    selectedItemTextStyle: TextStyle(
                        color: Colors.black,
                        fontSize: 16,
                        fontWeight: FontWeight.normal),
                    dropDownListTextStyle: TextStyle(
                        color: Colors.grey,
                        fontSize: 15,
                        backgroundColor: Colors.transparent),
                    onDropDownItemClick: (selectedItem) {
                      _selectedItem = selectedItem;
                    },
                    dropStateChanged: (isOpened) {
                      _isDropDownOpened = isOpened;
                      if (!isOpened) {
                        _isBackPressedOrTouchedOutSide = false;
                      }
                    },
                  ),
                ),
              ],
            ),
          ),
        ));
  }

  void _removeFocus() {
    if (_isDropDownOpened) {
      setState(() {
        _isBackPressedOrTouchedOutSide = true;
      });
      _navigateToPreviousScreenOnIOSBackPress = false;
    }
  }

  Future<bool> _onWillPop() {
    if (_scaffoldKey.currentState!.isEndDrawerOpen) {
      Navigator.of(context).pop();
      return Future.value(false);
    } else {
      if (_isDropDownOpened) {
        setState(() {
          _isBackPressedOrTouchedOutSide = true;
        });
        FocusManager.instance.primaryFocus!.unfocus();
        return Future.value(false);
      } else {
        if (_navigateToPreviousScreenOnIOSBackPress) {
          Navigator.of(context).pop();
          return Future.value(true);
        } else {
          _navigateToPreviousScreenOnIOSBackPress = true;
          return Future.value(false);
        }
      }
    }
  }

  void _onDrawerBtnPressed() {
    if (_isDropDownOpened) {
      setState(() {
        _isBackPressedOrTouchedOutSide = true;
      });
    } else {
      _scaffoldKey.currentState!.openEndDrawer();
      FocusScope.of(context).requestFocus(FocusNode());
    }
  }
}

更多关于Flutter下拉选择插件awesome_dropdown的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter下拉选择插件awesome_dropdown的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用awesome_dropdown插件的一个示例代码案例。awesome_dropdown是一个强大的下拉选择插件,它提供了丰富的功能和自定义选项。

首先,确保你的Flutter项目中已经添加了awesome_dropdown依赖。在pubspec.yaml文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  awesome_dropdown: ^2.0.0  # 请检查最新版本号

然后运行flutter pub get来获取依赖。

接下来,你可以在你的Dart文件中使用AwesomeDropdown。下面是一个完整的示例,展示如何设置和使用AwesomeDropdown

import 'package:flutter/material.dart';
import 'package:awesome_dropdown/awesome_dropdown.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  String? selectedValue;
  List<String> dropdownItems = ['Option 1', 'Option 2', 'Option 3', 'Option 4'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Awesome Dropdown Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              'Select an option:',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 10),
            AwesomeDropdown(
              isExpanded: true,
              listSource: dropdownItems,
              value: selectedValue,
              onChanged: (newValue) {
                setState(() {
                  selectedValue = newValue;
                });
              },
              dropdownDecoration: InputDecoration(
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(5),
                ),
                contentPadding: EdgeInsets.fromLTRB(10, 5, 10, 5),
                isDense: true,
                labelText: 'Choose an option',
                hintText: 'Select...',
              ),
              dropdownSearchDecoration: InputDecoration(
                labelText: 'Search...',
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.search),
              ),
              itemCount: dropdownItems.length,
              displayString: (value) {
                return dropdownItems[dropdownItems.indexOf(value!)!];
              },
              popupItemBuilder: <String, Widget>{
                'default': (context, item) {
                  return ListTile(
                    leading: Icon(Icons.label),
                    title: Text(item),
                  );
                },
              },
            ),
            SizedBox(height: 20),
            Text(
              'Selected Value: $selectedValue',
              style: TextStyle(fontSize: 16),
            ),
          ],
        ),
      ),
    );
  }
}

解释

  1. 依赖项:确保在pubspec.yaml中添加了awesome_dropdown依赖。
  2. 状态管理:在_MyHomePageState类中,我们有一个selectedValue变量来存储选中的值,以及一个dropdownItems列表来存储下拉选项。
  3. AwesomeDropdown:使用AwesomeDropdown小部件,我们设置了isExpandedlistSourcevalueonChanged等属性。
  4. 装饰dropdownDecorationdropdownSearchDecoration属性用于自定义下拉框和搜索栏的外观。
  5. 显示字符串displayString函数用于显示选中的值。
  6. 弹出项构建器popupItemBuilder允许我们自定义下拉列表项的布局。

运行这个示例代码,你将看到一个带有搜索功能的下拉选择框,当你选择一个选项时,selectedValue将更新并显示在页面上。

回到顶部