[英]How to make drop down reusable in flutter
我想讓這個下拉列表可重復使用。 當我想使用它時。 我需要簡單地調用該下拉列表並傳遞值。 希望你理解這個問題:)
這是我嘗試過的一些代碼。
FormBuilder(
key: _fbKey,
autovalidate: true,
initialValue: {
'country': 5,
},
child: FormBuilderCustomField(
attribute: "name",
validators: [
FormBuilderValidators.required(),
],
formField: FormField(
// key: _fieldKey,
enabled: true,
builder: (FormFieldState<dynamic> field) {
return InputDecorator(
decoration: InputDecoration(
labelText: "Select Country",
contentPadding: EdgeInsets.only(top: 10.0, bottom: 0.0),
border: InputBorder.none,
errorText: field.errorText,
),
child: DropdownButton(
isExpanded: true,
items: ["One", "Two"].map((option) {
return DropdownMenuItem(
child: Text("$option"),
value: option,
);
}).toList(),
value: field.value,
onChanged: (value) {
field.didChange(value);
},
),
);
},
),
),
);
創建一個自定義 class 如下所示
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
class DropDown extends StatelessWidget {
final GlobalKey fbKey;
final String attribute, labelText;
final List<String> itemsList;
DropDown({
Key key,
@required this.fbKey,
this.attribute,
this.labelText,
this.itemsList,
}) : super(key: key);
@override
Widget build(BuildContext context) {
// TODO: implement build
return FormBuilder(
key: fbKey,
autovalidate: true,
initialValue: {
'country': 5,
},
child: FormBuilderCustomField(
attribute: attribute,
validators: [
FormBuilderValidators.required(),
],
formField: FormField(
// key: _fieldKey,
enabled: true,
builder: (FormFieldState<dynamic> field) {
return InputDecorator(
decoration: InputDecoration(
labelText: labelText,
contentPadding: EdgeInsets.only(top: 10.0, bottom: 0.0),
border: InputBorder.none,
errorText: field.errorText,
),
child: DropdownButton(
isExpanded: true,
items: itemsList.map((option) {
return DropdownMenuItem(
child: Text("$option"),
value: option,
);
}).toList(),
value: field.value,
onChanged: (value) {
field.didChange(value);
},
),
);
},
),
),
);
}
}
如下使用它
DropDown(
fbKey: _bfKey,
attribute: 'Name',
labelText: 'Select Country',
itemsList: ['One', 'Two'],
),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.