Skip to content

Instantly share code, notes, and snippets.

@ybakos
Last active March 1, 2020 21:10
Show Gist options
  • 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}'));
});
}
}
@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