Last active
March 1, 2020 21:10
-
-
Save ybakos/2769781ecd6844a38c37f4e751f41761 to your computer and use it in GitHub Desktop.
A StatefulWidget that Wraps a DropdownButtonFormField so that the selected value displays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// (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 Yes! Thank you. I apparently did not post the gist from the latest commit. I've fixed it.
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
@jonabantao Thanks for the suggestion!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In the ratingMenuItems, I think it should be generating maxRating items, instead of 4. Right?