如何在下拉列表的底部制作一个按钮
how to make a button at the bottom of the drop down list
创建我使用的弹出列表 dropdown_search
我想看到的设计示例
当我开始搜索列表的元素时,应该会弹出一个添加按钮
或者当我们开始搜索元素时按钮应该立即出现
下拉列表
按钮底部
我选择了库中所有可能的方法,但仍然无法使用添加按钮
所有代码
https://github.com/dimapichuev2000/test_dropdownbutton
main.dart
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:dropdown_search/dropdown_search.dart';
import 'package:test_dropdownbutton/gym_model.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData().copyWith(
primaryColor: Colors.amber,
colorScheme: ThemeData().colorScheme.copyWith(
primary: Colors.orange,
),
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _multiKey = GlobalKey<DropdownSearchState<String>>();
Widget _customDropDownExample(BuildContext context, GymModel? item) {
if (item == null) {
return const Text(
"Выберите фитнесс центр",
style:
TextStyle(fontSize: 15, color: Color.fromRGBO(33, 33, 33, 0.6)),
);
}
return Container(
child: (item.avatar == "")
? ListTile(
contentPadding: EdgeInsets.all(0),
leading: const CircleAvatar(
radius: 25,
backgroundColor: Colors.white,
backgroundImage: NetworkImage(
'https://img.icons8.com/ios/50/000000/gum-.png'),
),
title: Text(item.gym),
subtitle: Text(
item.location,
),
)
: ListTile(
contentPadding: const EdgeInsets.all(0),
leading: CircleAvatar(
radius: 25,
backgroundImage: NetworkImage(item.avatar ?? ''),
),
title: Text(item.gym),
subtitle: Text(
item.location,
),
),
);
}
Widget _exitPopup(BuildContext context) {
return Container(
decoration: const BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
),
padding: const EdgeInsets.only(top: 2),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
margin: EdgeInsets.all(8),
height: 30,
width: 30,
),
const Text(
"Фитнесс центр",
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w500),
),
IconButton(
icon: Image.asset(
'assets/button_X.png',
width: 25,
height: 25,
fit: BoxFit.fill,
),
iconSize: 25,
onPressed: () {
Navigator.of(context).pop();
},
)
],
),
);
}
Widget _customPopupItemBuilderExample(
BuildContext context, GymModel? item, bool isSelected) {
return Container(
decoration: !isSelected
? null
: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.white,
),
child: ListTile(
selected: isSelected,
title: Text(item?.gym ?? ''),
subtitle: Text(item?.location ?? ''),
leading: (item!.avatar == "")
? const CircleAvatar(
radius: 25,
backgroundColor: Colors.white,
backgroundImage: NetworkImage(
'https://img.icons8.com/ios/100/000000/gum-.png'),
)
: CircleAvatar(
radius: 25,
backgroundImage: NetworkImage(item.avatar ?? ''),
)),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Key value Pair - DropdownButton'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Container(
margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
child: SingleChildScrollView(
child: DropdownSearch<GymModel>(
mode: Mode.BOTTOM_SHEET,
showSearchBox: true,
compareFn: (item, selectedItem) => item?.id == selectedItem?.id,
scrollbarProps:ScrollbarProps(
radius: Radius.circular(20),
thickness: 4,
),
onFind: (String? filter) => getData(filter),
dropdownSearchDecoration: const InputDecoration(
filled: true,
fillColor: Color(0xFFE3E3E4),
hintText: "Выберите фитнесс центр",
border: OutlineInputBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10),
),
borderSide: BorderSide(
width: 0,
style: BorderStyle.none,
),
),
contentPadding: EdgeInsets.fromLTRB(12, 3, 0, 0),
),
popupSafeArea:
const PopupSafeAreaProps(top: true, bottom: true),
// labelText: "Выберите фитнесс центр ",
onChanged: (data) {
print(data);
},
maxHeight: 850,
dropdownBuilder: _customDropDownExample,
popupItemBuilder: _customPopupItemBuilderExample,
dropDownButton: Image.asset('assets/dropButton.png',
color: Color(0xFF79818A)),
popupTitle: _exitPopup(context),
popupShape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
),
),
searchFieldProps: TextFieldProps(
decoration: const InputDecoration(
prefixIcon: Icon(
Icons.search,
),
filled: true,
fillColor: Color(0xFFE3E3E4),
border: OutlineInputBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10),
),
borderSide: BorderSide(
width: 0,
style: BorderStyle.none,
),
),
contentPadding: EdgeInsets.fromLTRB(12, 12, 8,0),
// labelText: "Поиск",
hintText: "Поиск",
hintStyle: TextStyle(fontSize: 17)),
),
),
),
),
],
),
),
);
}
Future<List<GymModel>> getData(filter) async {
var response = await Dio().get(
"https://my-json-server.typicode.com/dimapichuev2000/JSON_TEST/posts",
queryParameters: {"filter": filter},
);
final data = response.data;
if (data != null) {
return GymModel.fromJsonList(data);
}
return [];
}
}
gym_model.dart
class GymModel {
final String id;
final String location;
final String gym;
final String? avatar;
GymModel(
{required this.id,
required this.location,
required this.gym,
this.avatar});
factory GymModel.fromJson(Map<String, dynamic> json) {
return GymModel(
id: json["id"],
location: json["location"],
gym: json["gym"],
avatar: json["avatar"],
);
}
static List<GymModel> fromJsonList(List list) {
return list.map((item) => GymModel.fromJson(item)).toList();
}
@override
String toString() => gym;
}
pubspec.yaml
name: fitsupp_coach
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter_localizations:
sdk: flutter
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
pinput: ^1.2.2
intl: ^0.17.0
quiver: ^3.0.1+1
firebase_auth: ^3.3.5
firebase_core: ^1.11.0
dropdown_search: ^2.0.1
dio: ^4.0.4
provider: ^6.0.2
percent_indicator: ^4.0.0
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^1.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- assets/images/
- assets/images/DropDown/
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
fonts:
- family: SF Pro Display
fonts:
- asset: fontsassets/SFProDisplay/SFProDisplay-Light.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Medium.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Black.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Bold.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Heavy.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Regular.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Semibold.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Thin.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Ultralight.ttf
style: normal
- family: SF Pro Text
fonts:
- asset: fontsassets/SFProText/SF-Pro-Text-Light.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Medium.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Black.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Bold.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Heavy.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Regular.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Semibold.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Thin.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Ultralight.otf
style: normal
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
flutter_intl:
enabled: true
有很多方法可以做到这一点,但我认为最简单、最优雅的解决方案如下:
Column(
children: [
Flexible(
child: ListView.builder(
shrinkWrap: true,
itemCount: 5,
itemBuilder: (BuildContext context, int i) {
return Text(i.toString());
},
),
),
ElevatedButton.icon(
onPressed: null,
icon: const Icon(Icons.abc),
label: const Text('next')),
],
);
从 Column
小部件开始,然后添加 ListView.builder
和您选择的按钮,我使用 ElevatedButton.icon
,因为它是子项。现在将 ListView.builder
中的 shrinkWrap
设置设置为 true
,最后用 Flexible
小部件包裹它。
在你的情况下,你可以用 ListView.builder
小部件包装你的 Container
小部件,如果你得到 viewport.dart
错误,只需用 Flexible
或 [= 包装它24=],取决于您希望它消耗多少 space。然后你可以添加逻辑来检查你是否在最后 index
,在这种情况下你可以显示你的按钮,这有点像它最终看起来的代码:
Flexible(
child: ListView.builder(
shrinkWrap: true,
itemCount: _listSavedOutsideThisWidget.length+1,
itemBuilder: (BuildContext context, int index) {
if (index == _listSavedOutsideThisWidget.length) {
return TextButton.icon(
onPressed: _onPressed(context),
icon: const Icon(Icons.upload_file),
label: const Text('Upload Data'));
}
return Container(
decoration: !isSelected
? null
: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.white,
),
child: ListTile(
selected: isSelected,
title: Text(item?.gym ?? ''),
subtitle: Text(item?.location ?? ''),
leading: (item!.avatar == "")
? const CircleAvatar(
radius: 25,
backgroundColor: Colors.white,
backgroundImage: NetworkImage(
'https://img.icons8.com/ios/100/000000/gum-.png'),
)
: CircleAvatar(
radius: 25,
backgroundImage: NetworkImage(item.avatar ?? ''),
)),
);
},
),
);
要使此方法起作用,您必须在构建函数之外创建一个 List<GymModel> _listSavedOutsideThisWidget = []
变量,并通过更改 DropdownSearch
小部件下的 onFind
方法来填充它,如下所示:
onFind: (String? filter) async {
List<GymModel>> filteredList = await gedtData(filter);
setState(() => _listSavedOutsideThisWidget = filteredList);
// return getData(filter);
return filteredList; // if this doesn't work, try uncommenting the above line
}
希望这对您有所帮助。欢迎提出更多问题。
好的,这可能不是最优雅的解决方案,但它可以解决问题。
首先为按钮创建一个Model
:
class BottomButton {
final String? text;
BottomButton({
this.text,
});
}
然后您将要将所有输出类型从 GymModel?
更改为 dynamic
:
Widget _customDropDownExample(BuildContext context, dynamic item)
Widget _customPopupItemBuilderExample(
BuildContext context, dynamic item, bool isSelected)
DropdownSearch<dynamic>
Future<List<dynamic>> getData(filter)
现在,在检查 item == null
的 _customDropDownExample
函数中添加另一个以查看是否 item is !GymModel
:
if (item == null || item is !GymModel) {
return const Text(
"Выберите фитнесс центр",
style: TextStyle(fontSize: 15, color: Color.fromRGBO(33, 33, 33, 0.6)),
);
}
在 _customPopupItemBuilderExample
函数中检查 item is GymModel
是否是,如果是,则完全按照您之前的操作执行,如果不是,则创建您选择的按钮小部件,我使用了 ElevatedButton
为简单起见:
if (item is GymModel) {
return Container(
decoration: !isSelected
? null
: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.white,
),
child: ListTile(
selected: isSelected,
title: Text(item.gym),
subtitle: Text(item.location),
leading: (item.avatar == "")
? const CircleAvatar(
radius: 25,
backgroundColor: Colors.white,
backgroundImage: NetworkImage("https://picsum.photos/200"),
)
: CircleAvatar(
radius: 25,
backgroundImage: NetworkImage(item.avatar ?? ''),
)),
);
} else {
return ElevatedButton(onPressed: () {}, child: Text(item.text));
}
同时编写另一个函数来过滤结果并将其分配给 DropDownSearch
小部件中的 filterFn
属性:
bool _filterItems(dynamic item, String? str) {
if (item is GymModel) {
return (item.gym.toLowerCase().contains(str!.toLowerCase()) ||
item.location.toLowerCase().contains(str.toLowerCase()));
}
return (item is BottomButton);
}
最后在 getData
函数中检查 data != null
是否将按钮模型(BottomButton
,在我的例子中)添加到列表中:
Future<List<dynamic>> getData(filter) async {
var response = await Dio().get(
"https://my-json-server.typicode.com/dimapichuev2000/JSON_TEST/posts",
queryParameters: {"filter": filter},
);
final data = response.data;
if (data != null) {
List<dynamic> res = GymModel.fromJsonList(data);
BottomButton button = BottomButton(text: "Good Luck!");
return [...res, button];
}
return [];
}
创建我使用的弹出列表 dropdown_search
我想看到的设计示例
当我开始搜索列表的元素时,应该会弹出一个添加按钮
或者当我们开始搜索元素时按钮应该立即出现
下拉列表
按钮底部
我选择了库中所有可能的方法,但仍然无法使用添加按钮
所有代码 https://github.com/dimapichuev2000/test_dropdownbutton
main.dart
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:dropdown_search/dropdown_search.dart';
import 'package:test_dropdownbutton/gym_model.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData().copyWith(
primaryColor: Colors.amber,
colorScheme: ThemeData().colorScheme.copyWith(
primary: Colors.orange,
),
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _multiKey = GlobalKey<DropdownSearchState<String>>();
Widget _customDropDownExample(BuildContext context, GymModel? item) {
if (item == null) {
return const Text(
"Выберите фитнесс центр",
style:
TextStyle(fontSize: 15, color: Color.fromRGBO(33, 33, 33, 0.6)),
);
}
return Container(
child: (item.avatar == "")
? ListTile(
contentPadding: EdgeInsets.all(0),
leading: const CircleAvatar(
radius: 25,
backgroundColor: Colors.white,
backgroundImage: NetworkImage(
'https://img.icons8.com/ios/50/000000/gum-.png'),
),
title: Text(item.gym),
subtitle: Text(
item.location,
),
)
: ListTile(
contentPadding: const EdgeInsets.all(0),
leading: CircleAvatar(
radius: 25,
backgroundImage: NetworkImage(item.avatar ?? ''),
),
title: Text(item.gym),
subtitle: Text(
item.location,
),
),
);
}
Widget _exitPopup(BuildContext context) {
return Container(
decoration: const BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
),
padding: const EdgeInsets.only(top: 2),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
margin: EdgeInsets.all(8),
height: 30,
width: 30,
),
const Text(
"Фитнесс центр",
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w500),
),
IconButton(
icon: Image.asset(
'assets/button_X.png',
width: 25,
height: 25,
fit: BoxFit.fill,
),
iconSize: 25,
onPressed: () {
Navigator.of(context).pop();
},
)
],
),
);
}
Widget _customPopupItemBuilderExample(
BuildContext context, GymModel? item, bool isSelected) {
return Container(
decoration: !isSelected
? null
: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.white,
),
child: ListTile(
selected: isSelected,
title: Text(item?.gym ?? ''),
subtitle: Text(item?.location ?? ''),
leading: (item!.avatar == "")
? const CircleAvatar(
radius: 25,
backgroundColor: Colors.white,
backgroundImage: NetworkImage(
'https://img.icons8.com/ios/100/000000/gum-.png'),
)
: CircleAvatar(
radius: 25,
backgroundImage: NetworkImage(item.avatar ?? ''),
)),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Key value Pair - DropdownButton'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Container(
margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
child: SingleChildScrollView(
child: DropdownSearch<GymModel>(
mode: Mode.BOTTOM_SHEET,
showSearchBox: true,
compareFn: (item, selectedItem) => item?.id == selectedItem?.id,
scrollbarProps:ScrollbarProps(
radius: Radius.circular(20),
thickness: 4,
),
onFind: (String? filter) => getData(filter),
dropdownSearchDecoration: const InputDecoration(
filled: true,
fillColor: Color(0xFFE3E3E4),
hintText: "Выберите фитнесс центр",
border: OutlineInputBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10),
),
borderSide: BorderSide(
width: 0,
style: BorderStyle.none,
),
),
contentPadding: EdgeInsets.fromLTRB(12, 3, 0, 0),
),
popupSafeArea:
const PopupSafeAreaProps(top: true, bottom: true),
// labelText: "Выберите фитнесс центр ",
onChanged: (data) {
print(data);
},
maxHeight: 850,
dropdownBuilder: _customDropDownExample,
popupItemBuilder: _customPopupItemBuilderExample,
dropDownButton: Image.asset('assets/dropButton.png',
color: Color(0xFF79818A)),
popupTitle: _exitPopup(context),
popupShape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
),
),
searchFieldProps: TextFieldProps(
decoration: const InputDecoration(
prefixIcon: Icon(
Icons.search,
),
filled: true,
fillColor: Color(0xFFE3E3E4),
border: OutlineInputBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10),
),
borderSide: BorderSide(
width: 0,
style: BorderStyle.none,
),
),
contentPadding: EdgeInsets.fromLTRB(12, 12, 8,0),
// labelText: "Поиск",
hintText: "Поиск",
hintStyle: TextStyle(fontSize: 17)),
),
),
),
),
],
),
),
);
}
Future<List<GymModel>> getData(filter) async {
var response = await Dio().get(
"https://my-json-server.typicode.com/dimapichuev2000/JSON_TEST/posts",
queryParameters: {"filter": filter},
);
final data = response.data;
if (data != null) {
return GymModel.fromJsonList(data);
}
return [];
}
}
gym_model.dart
class GymModel {
final String id;
final String location;
final String gym;
final String? avatar;
GymModel(
{required this.id,
required this.location,
required this.gym,
this.avatar});
factory GymModel.fromJson(Map<String, dynamic> json) {
return GymModel(
id: json["id"],
location: json["location"],
gym: json["gym"],
avatar: json["avatar"],
);
}
static List<GymModel> fromJsonList(List list) {
return list.map((item) => GymModel.fromJson(item)).toList();
}
@override
String toString() => gym;
}
pubspec.yaml
name: fitsupp_coach
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter_localizations:
sdk: flutter
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
pinput: ^1.2.2
intl: ^0.17.0
quiver: ^3.0.1+1
firebase_auth: ^3.3.5
firebase_core: ^1.11.0
dropdown_search: ^2.0.1
dio: ^4.0.4
provider: ^6.0.2
percent_indicator: ^4.0.0
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^1.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- assets/images/
- assets/images/DropDown/
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
fonts:
- family: SF Pro Display
fonts:
- asset: fontsassets/SFProDisplay/SFProDisplay-Light.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Medium.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Black.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Bold.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Heavy.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Regular.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Semibold.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Thin.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Ultralight.ttf
style: normal
- family: SF Pro Text
fonts:
- asset: fontsassets/SFProText/SF-Pro-Text-Light.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Medium.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Black.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Bold.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Heavy.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Regular.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Semibold.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Thin.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Ultralight.otf
style: normal
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
flutter_intl:
enabled: true
有很多方法可以做到这一点,但我认为最简单、最优雅的解决方案如下:
Column(
children: [
Flexible(
child: ListView.builder(
shrinkWrap: true,
itemCount: 5,
itemBuilder: (BuildContext context, int i) {
return Text(i.toString());
},
),
),
ElevatedButton.icon(
onPressed: null,
icon: const Icon(Icons.abc),
label: const Text('next')),
],
);
从 Column
小部件开始,然后添加 ListView.builder
和您选择的按钮,我使用 ElevatedButton.icon
,因为它是子项。现在将 ListView.builder
中的 shrinkWrap
设置设置为 true
,最后用 Flexible
小部件包裹它。
在你的情况下,你可以用 ListView.builder
小部件包装你的 Container
小部件,如果你得到 viewport.dart
错误,只需用 Flexible
或 [= 包装它24=],取决于您希望它消耗多少 space。然后你可以添加逻辑来检查你是否在最后 index
,在这种情况下你可以显示你的按钮,这有点像它最终看起来的代码:
Flexible(
child: ListView.builder(
shrinkWrap: true,
itemCount: _listSavedOutsideThisWidget.length+1,
itemBuilder: (BuildContext context, int index) {
if (index == _listSavedOutsideThisWidget.length) {
return TextButton.icon(
onPressed: _onPressed(context),
icon: const Icon(Icons.upload_file),
label: const Text('Upload Data'));
}
return Container(
decoration: !isSelected
? null
: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.white,
),
child: ListTile(
selected: isSelected,
title: Text(item?.gym ?? ''),
subtitle: Text(item?.location ?? ''),
leading: (item!.avatar == "")
? const CircleAvatar(
radius: 25,
backgroundColor: Colors.white,
backgroundImage: NetworkImage(
'https://img.icons8.com/ios/100/000000/gum-.png'),
)
: CircleAvatar(
radius: 25,
backgroundImage: NetworkImage(item.avatar ?? ''),
)),
);
},
),
);
要使此方法起作用,您必须在构建函数之外创建一个 List<GymModel> _listSavedOutsideThisWidget = []
变量,并通过更改 DropdownSearch
小部件下的 onFind
方法来填充它,如下所示:
onFind: (String? filter) async {
List<GymModel>> filteredList = await gedtData(filter);
setState(() => _listSavedOutsideThisWidget = filteredList);
// return getData(filter);
return filteredList; // if this doesn't work, try uncommenting the above line
}
希望这对您有所帮助。欢迎提出更多问题。
好的,这可能不是最优雅的解决方案,但它可以解决问题。
首先为按钮创建一个Model
:
class BottomButton {
final String? text;
BottomButton({
this.text,
});
}
然后您将要将所有输出类型从 GymModel?
更改为 dynamic
:
Widget _customDropDownExample(BuildContext context, dynamic item)
Widget _customPopupItemBuilderExample(
BuildContext context, dynamic item, bool isSelected)
DropdownSearch<dynamic>
Future<List<dynamic>> getData(filter)
现在,在检查 item == null
的 _customDropDownExample
函数中添加另一个以查看是否 item is !GymModel
:
if (item == null || item is !GymModel) {
return const Text(
"Выберите фитнесс центр",
style: TextStyle(fontSize: 15, color: Color.fromRGBO(33, 33, 33, 0.6)),
);
}
在 _customPopupItemBuilderExample
函数中检查 item is GymModel
是否是,如果是,则完全按照您之前的操作执行,如果不是,则创建您选择的按钮小部件,我使用了 ElevatedButton
为简单起见:
if (item is GymModel) {
return Container(
decoration: !isSelected
? null
: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.white,
),
child: ListTile(
selected: isSelected,
title: Text(item.gym),
subtitle: Text(item.location),
leading: (item.avatar == "")
? const CircleAvatar(
radius: 25,
backgroundColor: Colors.white,
backgroundImage: NetworkImage("https://picsum.photos/200"),
)
: CircleAvatar(
radius: 25,
backgroundImage: NetworkImage(item.avatar ?? ''),
)),
);
} else {
return ElevatedButton(onPressed: () {}, child: Text(item.text));
}
同时编写另一个函数来过滤结果并将其分配给 DropDownSearch
小部件中的 filterFn
属性:
bool _filterItems(dynamic item, String? str) {
if (item is GymModel) {
return (item.gym.toLowerCase().contains(str!.toLowerCase()) ||
item.location.toLowerCase().contains(str.toLowerCase()));
}
return (item is BottomButton);
}
最后在 getData
函数中检查 data != null
是否将按钮模型(BottomButton
,在我的例子中)添加到列表中:
Future<List<dynamic>> getData(filter) async {
var response = await Dio().get(
"https://my-json-server.typicode.com/dimapichuev2000/JSON_TEST/posts",
queryParameters: {"filter": filter},
);
final data = response.data;
if (data != null) {
List<dynamic> res = GymModel.fromJsonList(data);
BottomButton button = BottomButton(text: "Good Luck!");
return [...res, button];
}
return [];
}