我正在尝试为用户填写费用表格,我想获取费用类别。我已经创建了包含所有项目和所有项目的下拉按钮,但是我希望用户能够输入自定义类别。为此,我创建了一个名为other的类别,当用户单击该类别时,下拉按钮将替换为TextField和Icon按钮,如果用户选择改为选择该类别,则再次显示Dropdown。除“图标”按钮外,其他所有功能均正常。它什么也没做,有人可以向我解释为什么吗?
码:
import 'package:flutter/material.dart';
class UserPage extends StatefulWidget {
@override
_UserPageState createState() => _UserPageState();
}
class _UserPageState extends State<UserPage> {
List<List> categories = [
['food', Icon(Icons.fastfood)],
['clothing', Icon(Icons.shopping_basket)],
['electronics', Icon(Icons.computer)],
['accessories', Icon(Icons.blur_circular)],
['transportation', Icon(Icons.local_taxi)],
['gain', Icon(Icons.attach_money)],
['other', Icon(Icons.radio_button_unchecked)]
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add Purchase Dialog'),
),
body: Center(
child: IconButton(
icon: Icon(Icons.add_circle),
onPressed: () {
createPurchase(context);
},
)));
}
void createPurchase(BuildContext context) {
final _formKey = GlobalKey<FormState>();
final priceController = TextEditingController();
final otherCategoryController = TextEditingController();
var _selectedCategory;
bool otherSelected = false;
double dialogHeight = 187;
List<DropdownMenuItem> menuItems = [];
for (var category in categories) {
menuItems.add(DropdownMenuItem(
value: (category[0] != 'other')
? category[0]
: otherCategoryController.text,
child: Row(
children: <Widget>[
category[1],
SizedBox(width: 5),
Text(category[0]),
],
)));
}
showDialog(
context: context,
builder: (context) => Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)),
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Container(
padding: EdgeInsets.fromLTRB(20, 10, 20, 0),
height: dialogHeight,
width: 300,
child: Column(
children: <Widget>[
Text('Add a purchase'),
Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
otherSelected
? Row(
children: <Widget>[
SizedBox(
width: 184,
height: 20,
child: TextFormField(
controller:
otherCategoryController,
decoration: InputDecoration(
hintText: 'Other Category'),
)),
IconButton(
icon: Icon(Icons.arrow_drop_down),
onPressed: () {
setState() => otherSelected =
!otherSelected;
})
],
)
: DropdownButtonFormField(
hint: Text('Category'),
items: menuItems,
onChanged: (category) => setState(() {
_selectedCategory = category;
(category == 'other')
? otherSelected = true
: null;
}),
value: _selectedCategory,
validator: (val) => (val == null)
? 'Select a category'
: null,
),
TextFormField(
decoration: InputDecoration(hintText: 'Amount'),
controller: priceController,
keyboardType: TextInputType.number,
validator: (val) =>
(val == null) ? 'enter an amount' : null,
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
FlatButton(
child: Text('Continue'), onPressed: null),
],
),
],
),
)
],
),
);
},
),
));
}
}
非常感谢您的帮助。