Skip to content

Instantly share code, notes, and snippets.

@ybakos
Last active March 1, 2020 21:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ybakos/2769781ecd6844a38c37f4e751f41761 to your computer and use it in GitHub Desktop.
Save ybakos/2769781ecd6844a38c37f4e751f41761 to your computer and use it in GitHub Desktop.
A StatefulWidget that Wraps a DropdownButtonFormField so that the selected value displays
// (c) 2020 Yong Joseph Bakos. Use this freely.
// https://github.com/flutter/flutter/issues/27821
// Usage:
// DropdownRatingFormField(
// maxRating: 4,
// validator: (value) { /* ... */ },
// onSaved: (value) { /* ... */ }
// );
import 'package:flutter/material.dart';
class DropdownRatingFormField extends StatefulWidget {
final int maxRating;
final void Function(dynamic) onSaved;
final String Function(dynamic) validator;
DropdownRatingFormField({Key key, this.maxRating, this.onSaved, this.validator}) : super(key: key);
@override
DropdownRatingFormFieldState createState() => DropdownRatingFormFieldState();
}
class DropdownRatingFormFieldState extends State<DropdownRatingFormField> {
int selectedValue;
@override
Widget build(BuildContext context) {
return DropdownButtonFormField(
value: selectedValue,
items: ratingMenuItems(maxRating: widget.maxRating),
onChanged: (value) {
setState( () => selectedValue = value );
},
decoration: InputDecoration(
labelText: 'Rating',
border: OutlineInputBorder()
),
validator: widget.validator,
onSaved: widget.onSaved
);
}
List<DropdownMenuItem> ratingMenuItems({int maxRating}) {
return List<DropdownMenuItem>.generate(maxRating, (i) {
return DropdownMenuItem(value: i+1, child: Text('${i+1}'));
});
}
}
@JSeawell
Copy link

JSeawell commented Feb 22, 2020

In the ratingMenuItems, I think it should be generating maxRating items, instead of 4. Right?

@ybakos
Copy link
Author

ybakos commented Feb 22, 2020

@JSeawell Yes! Thank you. I apparently did not post the gist from the latest commit. I've fixed it.

@jonabantao
Copy link

A little bit late now that the project is almost over - but if this code will be reused in future classes, set isDense in DropdownButtonFormField to true? Or else the height of this field will be larger than the two other fields in the form

@ybakos
Copy link
Author

ybakos commented Mar 1, 2020

@jonabantao Thanks for the suggestion!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment