How to get selectedIndex of dropdown in flutter,
In dropdownbutton there is no property to get selected index, if there how to get the selected index and my code look like this:
new DropdownButton( hint:new Text("Select a users"),value: selectedUser,
onChanged: (String newValue) {
setState(() {
selectedUser = newValue;
});
},
items: userInfoToMap.map((ListOfUsers value) {
return new DropdownMenuItem<String>(
value: value.name,
child:new Text(value.name,style: new TextStyle(color: Colors.black))
);
})
.toList(),
),
),),
You should probably use a custom model object (e.g. User) as the type for DropdownButton.
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class User {
const User(this.name);
final String name;
}
class MyApp extends StatefulWidget {
State createState() => new MyAppState();
}
class MyAppState extends State<MyApp> {
User selectedUser;
List<User> users = <User>[User('Foo'), User('Bar')];
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
body: new Center(
child: new DropdownButton<User>(
hint: new Text("Select a user"),
value: selectedUser,
onChanged: (User newValue) {
setState(() {
selectedUser = newValue;
});
},
items: users.map((User user) {
return new DropdownMenuItem<User>(
value: user,
child: new Text(
user.name,
style: new TextStyle(color: Colors.black),
),
);
}).toList(),
),
),
),
);
}
}
Similar to Collin Jackson's answer, you can simply use a List of Strings and check the indexOf to set the value, which might be preferable in some situations rather than making a User class.
If you want to set an initial value set _user to an integer value when defined.
int _user;
...
var users = <String>[
'Bob',
'Allie',
'Jason',
];
return new DropdownButton<String>(
hint: new Text('Pickup on every'),
value: _user == null ? null : users[_user],
items: users.map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
onChanged: (value) {
setState(() {
_user = users.indexOf(value);
});
},
);
This gives you selected index of your dropdown
userInfoToMap.indexOf(selectedUser);
Related
I have no problem populating the list from Sqflite database on DropdownButton. My only problem is updating the text once it's selected. It kept showing 'Airport' and I'm still learning to work with Object instead of String. I just couldn't figure that out.
Here's the code:
String selectedAirport;
AirportModel _currentAirport;
...
children: <Widget>[
FutureBuilder<List<AirportModel>>(
future: db.getAllAirports(),
builder: (BuildContext context, AsyncSnapshot<List<AirportModel>> snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
return DropdownButton<AirportModel>(
items: snapshot.data
.map((airportItem) =>
DropdownMenuItem<AirportModel>(
value: airportItem,
child: Text(airportItem.airportName),
))
.toList(),
onChanged: (AirportModel value) {
setState(() {
_currentAirport = value;
selectedAirport = _currentAirport.airportName;
});
},
hint: Text("Airport"),
);
}),
DropdownButton has a property value. use it like value=_currentAirport
return DropdownButton<AirportModel>(
value:_currentAirport,
items: snapshot.data
.map((airportItem) =>
DropdownMenuItem<AirportModel>(
value: airportItem,
child: Text(airportItem.airportName),
))
.toList(),
onChanged: (AirportModel value) {
setState(() {
_currentAirport = value;
selectedAirport = _currentAirport.airportName;
});
},
hint: Text("Airport"),
);
Maybe items didn't reach yet or empty when value is set to DropdownButton. is _currentAirport initialized to some other value already?
Can you try like this? Also check if the items list are empty
items: snapshot.data == null ? null : _currentAirport
You can declare a Future and init in initState and in FutureBuilder use this future.
AirportModel _currentAirport;;
Future _future;
#override
void initState() {
_future = db.getAllAirports();
super.initState();
}
body: FutureBuilder<List<AirportModel>>(
future: _future,
You can use stream builder. Please check the example below.
class DropDownMenu extends StatefulWidget {
#override
_DropDownMenuState createState() => _DropDownMenuState();
}
class _DropDownMenuState extends State<DropDownMenu> {
var _currentSelectedValue;
final _dbHelper = DatabaseHelper.instance;
LoginPageManager _loginPageManager = new LoginPageManager();
final ValueNotifier<List<DropdownMenuItem<String>>> _dropDownMenuItems =
ValueNotifier<List<DropdownMenuItem<String>>>([]);
#override
void initState() {
_updateList();
super.initState();
}
#override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
width: 300,
height: 50,
margin: const EdgeInsets.only(top: 00.0),
child: ValueListenableBuilder(
builder: (BuildContext context, List<DropdownMenuItem<String>> list,
Widget child) {
return Container(
child: DropdownButton<String>(
hint: Text("Please Select a Server"),
value: _currentSelectedValue,
onChanged: (value) {
setState(() {
_currentSelectedValue = value;
});
},
items: list),
);
},
valueListenable: _dropDownMenuItems,
),
);
}
_updateList() async {
print("Update server has been called");
_dropDownMenuItems.value.clear();
List<Map<String, dynamic>> x = await _dbHelper.queryAllRows();
_dropDownMenuItems.value.add(_getAddServerButton());
x.forEach((element) {
_dropDownMenuItems.value.add(_getDropDownWidget(element));
});
}
DropdownMenuItem<String> _getDropDownWidget(Map<String, dynamic> map) {
int id = map['yxz'];
String text =
map['xyz'];
String value = map['zyx'];
return DropdownMenuItem<String>(
value: value,
child: Container(
width: 270,
child: Row(
children: [_getText(text), _getRemoveButton(id), _getEditButton(id)],
),
));
}
}
To make sure api data is not null:
child: _identity1 != null
? DropdownButtonFormField<dynamic>(
validator: (value) => value == null ? 'field required' : null
I am trying to pass data from one screen to another, but I keep getting a null exception. Whenever I fill in the form on the first screen and proceed to next screen, I get a `
NoSuchMethodError: The getter 'storeNumber' was called on null
`
My variables class is ==> This entity class has variables that I populate using a form in the following class:
class StoreData {
String _storeNumber;
String _repName;
String _repCell;
DateTime _transactionDate = new DateTime.now();
StoreData(
this._storeNumber, this._repName, this._repCell, this._transactionDate);
String get storeNumber => _storeNumber;
set storeNumber(String value) {
_storeNumber = value;
}
String get repName => _repName;
DateTime get transactionDate => _transactionDate;
set transactionDate(DateTime value) {
_transactionDate = value;
}
String get repCell => _repCell;
set repCell(String value) {
_repCell = value;
}
set repName(String value) {
_repName = value;
}
}
The main class (in this case this is the first screen that sends data to second screen) includes the following code:
This class has a form that takes in 3 inputs and send them to second screen.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'FeedBack.dart';
import 'StoreData.dart';
void main() {
runApp(MaterialApp(
title: 'Navigation Basics',
home: FirstScreen(),
));
}
//get our entity class
StoreData storeDate;
// get variables from entity class
String storeNumber = storeDate.storeNumber;
String repName = storeDate.repName;
String repCell = storeDate.repCell;
DateTime transactionDate = storeDate.transactionDate;
class FirstScreen extends StatefulWidget {
#override
_FirstScreenState createState() => _FirstScreenState();
}
class _FirstScreenState extends State<FirstScreen> {
GlobalKey<FormState> _key = GlobalKey();
bool _validate = false;
_sendData() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FeedBack(
storeData: new StoreData(
storeNumber, repName, repCell, transactionDate))),
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text('Test App'),
),
body: new SingleChildScrollView(
child: new Container(
margin: new EdgeInsets.all(15.0),
child: new Form(
key: _key,
autovalidate: _validate,
child: formUI(),
),
),
),
),
);
}
Widget formUI() {
return new Column(
children: <Widget>[
new TextFormField(
decoration: new InputDecoration(hintText: 'Store Number'),
keyboardType: TextInputType.number,
validator: validateRepCell,
onSaved: (String val) {
storeNumber = val;
}),
new TextFormField(
decoration: new InputDecoration(hintText: 'Rep Full Name'),
validator: validateRepName,
onSaved: (String val) {
repName = val;
}),
new TextFormField(
decoration: new InputDecoration(hintText: 'Rep Phone Number'),
keyboardType: TextInputType.number,
validator: validateRepCell,
onSaved: (String val) {
repCell = val;
}),
new SizedBox(height: 15.0),
new RaisedButton(
onPressed: _sendData,
child: new Text('Proceed'),
)
],
);
}
// Validate Fields
String validateRepCell(String value) {
// String patttern = r'(^[a-zA-Z ]*$)';
RegExp regExp = new RegExp(r'^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$');
if (value.length == 0) {
return "Store Number is Required";
} else if (!regExp.hasMatch(value)) {
return "Store Number must be only have numbers";
}
return null;
}
String validateRepName(String value) {
String patttern = r'(^[a-zA-Z ]*$)';
RegExp regExp = new RegExp(patttern);
if (value.length == 0) {
return "Rep Name is Required";
} else if (!regExp.hasMatch(value)) {
return "Name must be a-z and A-Z";
}
return null;
}
}
The second screen's code is here:
class FeedBack extends StatelessWidget {
final StoreData storeData;
FeedBack({Key key, #required this.storeData}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("FeedBack Screen"),
),
body: new Container(
child: new Column(
children: <Widget>[
new RaisedButton(
onPressed: _sendToDatabase,
child: new Text('Press Me'),
),
new Text("${storeData.storeNumber}"),
],
),
),
);
}
_sendToDatabase() {
Firestore.instance.runTransaction((Transaction transaction) async {
CollectionReference reference = Firestore.instance.collection('Stores');
await reference.add({"test": "test", "testII": "test"});
});
}
}
I have been trying to solve this problem for a week now, but given my new experience with Dart and Flutter framework, it has been tough !
Any help would be appreciated,
You can use the following approach.
Remove the following lines from your code:
//get our entity class
StoreData storeDate;
As initially there will be no instance of StoreData available right now.
Now, declare new variables like the following:
String storeNumber;
String repName;
String repCell;
DateTime transactionDate;
And then assign the form values to them in onSaved method.
So when your form will be submitted, these values will be used for creating new StoreData and it will be passed to the Second page.
Here is the code for your main.dart file:
import 'package:flutter/material.dart';
import 'FeedBack.dart';
import 'StoreData.dart';
void main() {
runApp(MaterialApp(
title: 'Navigation Basics',
home: FirstScreen(),
));
}
// get variables from entity class
String storeNumber;
String repName;
String repCell;
DateTime transactionDate = DateTime.now();
class FirstScreen extends StatefulWidget {
#override
_FirstScreenState createState() => _FirstScreenState();
}
class _FirstScreenState extends State<FirstScreen> {
GlobalKey<FormState> _key = GlobalKey();
bool _validate = false;
_sendData() {
_key.currentState.save();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FeedBack(
storeData: StoreData(
storeNumber, repName, repCell, transactionDate))),
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text('Test App'),
),
body: new SingleChildScrollView(
child: new Container(
margin: new EdgeInsets.all(15.0),
child: new Form(
key: _key,
autovalidate: _validate,
child: formUI(),
),
),
),
),
);
}
Widget formUI() {
return new Column(
children: <Widget>[
new TextFormField(
decoration: new InputDecoration(hintText: 'Store Number'),
keyboardType: TextInputType.number,
validator: validateRepCell,
onSaved: (String val) {
storeNumber = val;
}),
new TextFormField(
decoration: new InputDecoration(hintText: 'Rep Full Name'),
validator: validateRepName,
onSaved: (String val) {
repName = val;
}),
new TextFormField(
decoration: new InputDecoration(hintText: 'Rep Phone Number'),
keyboardType: TextInputType.number,
validator: validateRepCell,
onSaved: (String val) {
repCell = val;
}),
new SizedBox(height: 15.0),
new RaisedButton(
onPressed: _sendData,
child: new Text('Proceed'),
)
],
);
}
// Validate Fields
String validateRepCell(String value) {
// String patttern = r'(^[a-zA-Z ]*$)';
RegExp regExp = new RegExp(r'^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$');
if (value.length == 0) {
return "Store Number is Required";
} else if (!regExp.hasMatch(value)) {
return "Store Number must be only have numbers";
}
return null;
}
String validateRepName(String value) {
String patttern = r'(^[a-zA-Z ]*$)';
RegExp regExp = new RegExp(patttern);
if (value.length == 0) {
return "Rep Name is Required";
} else if (!regExp.hasMatch(value)) {
return "Name must be a-z and A-Z";
}
return null;
}
}
I'm using floatingActionButton to increase TextForm Fields. i.e the fields increase by 1 once the button is tapped. The fields are actually increased on tap of the button but so confused on how to get values for each fields generated.
My problems:
When the user selects a value in the dropdown, all the values in the other generated dropdown fields changes to the new one. How do I solve this?
I'd like to add all the number value of the each of the generated Grade field together and also add the value of each of the generated Course Unit field together. i.e Add(sum) the value of all Grade fields the user generated.
See my full code below:
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'My Grade Point',
theme: new ThemeData(primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _isLoading = false;
final formKey = new GlobalKey<FormState>();
final scaffoldKey = new GlobalKey<ScaffoldState>();
String _course;
String _grade;
String _unit;
String _mygp;
String _units;
String _totalgrade;
int counter = 1;
void _submit() {
final form = formKey.currentState;
if (form.validate()) {
setState(() => _totalgrade = _grade);
form.save();
}
}
Widget buildfields(int index) {
return new Column(
children: <Widget>[
new TextFormField(
onSaved: (String value) {
setState((){
_course = value;
});
},
validator: (val) {
return val.isEmpty
? "Enter Course Title $index"
: null;
},
decoration: new InputDecoration(labelText: "Course Title"),
),
new Row(
children: <Widget>[
new Expanded(
child: new TextFormField(
onSaved: (value) {
setState((){
_grade = value;
});
},
keyboardType: TextInputType.number,
decoration: new InputDecoration(labelText: "Grade"),
),
),
new Expanded(
child: new DropdownButton<String>(
onChanged: (String value) { setState((){
_unit = value;
});
},
hint: new Text('Course Unit'),
value: _unit,
items: <String>["1", "2", "3", "4", "5"].map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
),
),
],
),
],
);
}
#override
Widget build(BuildContext context) {
final Size screenSize = MediaQuery.of(context).size;
var loginBtn = new RaisedButton(
onPressed: _submit,
child: new Text("CALCULATE"),
color: Colors.primaries[0],
);
var showForm = new Container(
padding: new EdgeInsets.all(20.0),
child: new Column(
children: <Widget>[
new Expanded(child: new Form(
key: formKey,
child: new ListView.builder(
itemBuilder: (BuildContext context, int index) {
return buildfields(index); },
itemCount: counter,
scrollDirection: Axis.vertical,
),
),
),
_isLoading ? new CircularProgressIndicator() : loginBtn
],
),
);
return new Scaffold(
appBar: new AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: new Text(_totalgrade.toString()),
),
body: showForm,
floatingActionButton: new FloatingActionButton(
onPressed: () {
setState(() {
counter++;
});
},
child: new Icon(Icons.add),
),
);
}
}
When the user selects a value in the dropdown, all the values in the other generated dropdown fields changes to the new one. How do I solve this?
The reason why DropdownButton children in ListView updates synchronously is because it fetches all its value from the _unit variable. I suggest using a List<Object> to manage the data of ListView items.
i.e.
class Course {
var title;
var grade;
var unit;
}
...
List<Course> _listCourse = [];
I'd like to add all the number value of the each of the generated Grade field together and also add the value of each of the generated Course Unit field together. i.e Add(sum) the value of all Grade fields the user generated.
With ListView data being managed in List<Course>, data inputted in the fields can be set in onChanged()
// Course Grade
TextFormField(
onChanged: (String value) {
setState(() {
_listCourse[index].grade = value;
});
},
)
and the values can be summed up with the help of a foreach loop.
int sumGrade = 0;
_listCourse.forEach((course) {
// Add up all Course Grade
sumGrade += num.tryParse(course.grade);
});
Here's a complete working sample based from the snippet you've shared.
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'My Grade Point',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class Course {
var title;
var grade;
var unit;
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _isLoading = false;
final formKey = new GlobalKey<FormState>();
final scaffoldKey = new GlobalKey<ScaffoldState>();
String _course;
int _grade;
String _unit;
String _mygp;
String _units;
int _totalGrade;
int counter = 1;
List<Course> _listCourse = [];
#override
void initState() {
// Initialize empty List
_listCourse.add(Course());
super.initState();
}
void _submit() {
debugPrint('List Course Length: ${_listCourse.length}');
int sumGrade = 0;
_listCourse.forEach((course) {
debugPrint('Course Title: ${course.title}');
debugPrint('Course Grade: ${course.grade}');
// Add up all Course Grade
sumGrade += num.tryParse(course.grade);
debugPrint('Course Unit: ${course.unit}');
});
final form = formKey.currentState;
if (form.validate()) {
setState(() => _totalGrade = sumGrade);
form.save();
}
}
Widget buildField(int index) {
return new Column(
children: <Widget>[
new TextFormField(
onChanged: (String value) {
setState(() {
// _course = value;
_listCourse[index].title = value;
});
},
validator: (val) {
return val.isEmpty ? "Enter Course Title $index" : null;
},
decoration: new InputDecoration(labelText: "Course Title"),
),
new Row(
children: <Widget>[
new Expanded(
child: new TextFormField(
onChanged: (value) {
setState(() {
// _grade = value;
_listCourse[index].grade = value;
});
},
keyboardType: TextInputType.number,
decoration: new InputDecoration(labelText: "Grade"),
),
),
new Expanded(
child: new DropdownButton<String>(
onChanged: (String value) {
setState(() {
// _unit = value;
_listCourse[index].unit = value;
});
},
hint: new Text('Course Unit'),
value: _listCourse[index].unit,
items: <String>["1", "2", "3", "4", "5"].map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
),
),
],
),
],
);
}
#override
Widget build(BuildContext context) {
final Size screenSize = MediaQuery.of(context).size;
var loginBtn = new RaisedButton(
onPressed: _submit,
child: new Text("CALCULATE"),
color: Colors.primaries[0],
);
var showForm = new Container(
padding: new EdgeInsets.all(20.0),
child: new Column(
children: <Widget>[
new Expanded(
child: new Form(
key: formKey,
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return buildField(index);
},
itemCount: counter,
scrollDirection: Axis.vertical,
),
),
),
_isLoading ? new CircularProgressIndicator() : loginBtn
],
),
);
return new Scaffold(
appBar: new AppBar(
title: new Text(_totalGrade.toString()),
),
body: showForm,
floatingActionButton: new FloatingActionButton(
onPressed: () {
setState(() {
// Add an empty Course object on the List
_listCourse.add(Course());
counter++;
});
},
child: new Icon(Icons.add),
),
);
}
}
I'm just starting with Flutter, finished the first codelab and tried to add some simple functionality to it.
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Startup Name Generator',
theme: new ThemeData(primaryColor: Colors.deepOrange),
home: new RandomWords(),
);
}
}
class RandomWords extends StatefulWidget {
#override
createState() => new RandomWordsState();
}
class RandomWordsState extends State<RandomWords> {
final _suggestions = <WordPair>[];
final _biggerFont = new TextStyle(fontSize: 18.0);
final _saved = new Set<WordPair>();
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Startup Name Generator'),
actions: <Widget>[
new IconButton(
icon: new Icon(Icons.list),
onPressed: _pushSaved,
)
],
),
body: _buildSuggestions(),
);
}
Widget _buildSuggestions() {
return new ListView.builder(
padding: const EdgeInsets.all(16.0),
itemBuilder: (context, i) {
if (i.isOdd) return new Divider();
final index = i ~/ 2;
if (index >= _suggestions.length) {
_suggestions.addAll(generateWordPairs().take(10));
}
return _buildRow(_suggestions[index]);
},
);
}
Widget _buildRow(WordPair pair) {
final alreadySaved = _saved.contains(pair);
return new ListTile(
title: new Text(
pair.asPascalCase,
style: _biggerFont,
),
trailing: new IconButton(
icon: new Icon(alreadySaved ? Icons.favorite : Icons.favorite_border),
color: alreadySaved ? Colors.red : null,
onPressed: () {
setState(() {
if (alreadySaved) {
_saved.remove(pair);
} else {
_saved.add(pair);
}
});
},
));
}
void _pushSaved() {
Navigator.of(context).push(
new MaterialPageRoute(
builder: (context) {
final tiles = _saved.map(
(pair) {
return _buildRow(pair);
// new ListTile(
// title: new Text(
// pair.asPascalCase,
// style: _biggerFont,
// ),
// );
},
);
final divided = ListTile
.divideTiles(
context: context,
tiles: tiles,
)
.toList();
return new Scaffold(
appBar: new AppBar(
title: new Text('Saved Suggestions'),
),
body: new ListView(children: divided),
);
},
),
);
}
}
In the Save suggestions screen I built the same row as in the Sugestions Screen.
In the Saved Sugstions screen when you click the heart icon the element is removed from the array of saved items but the screen is not re-rendered.
what am I doing wrong here?
thanks!
Update
Actually your app is working perfectly fine with me :/
Because you are not communicating the state change with the icon change. You are already changing state based on alreadySaved, notice how you managed setState()
setState(() {
if (alreadySaved) {
_saved.remove(pair);
} else {
_saved.add(pair);
}
});
In the previous block you are only removing or adding to your favourite list based on the boolean value of alreadySaved and you are not telling setState to change anything else. That is why the following does not produce a re-render even though alreadySaved is switching values
///These two lines do not know what is happening
icon: new Icon(alreadySaved ? Icons.favorite : Icons.favorite_border),
color: alreadySaved ? Colors.red : null,
So you can instead do the following
icon: new Icon(_whichIcon), //initialized var _whichIcon = Icons.favorite_border
color: _whichIconColor, //Initialized var _whichIconColor = Colors.transparent
And your setState would be:
setState(() {
if (alreadySaved) {
_saved.remove(pair);
_whichIcon = Icons.favorite_border ;
_whichIconColor = Colors.transparent;
} else {
_saved.add(pair);
_whichIcon = Icons.favorite ;
_whichIconColor = Colors.red;
}
});
Or simpler you can do it like this, and keep your icon logic unchanged:
bool alreadySaved = false;
...
setState(() {
if (_saved.contains(pair)) {
_saved.remove(pair);
alreadySaved = false;
} else {
_saved.add(pair);
alreadySaved = true;
}
});
I'm trying to create a popup menu that contains selectable radio buttons in order to change a view type (e.g. gallery, cards, swipe, grid, list, etc.).
The issue I'm running into is that PopupMenu has its own callbacks for selecting values, and so does Radio and RadioListTile.
Ignore RadioListTile's onChanged
Here's my first attempt. This actually works, except that the buttons are perpetually grayed out. Giving the RadioListTiles a non-null noop function results in the buttons no longer grayed out (disabled), but then the popup menu no longer works.
new PopupMenuButton<String>(
...
itemBuilder: (ctx) => <PopupMenuEntry<String>>[
new PopupMenuItem(
child: new RadioListTile(
title: new Text("Cards"),
value: 'cards',
groupValue: _view,
onChanged: null),
value: 'cards'),
new PopupMenuItem(
child: new RadioListTile(
title: new Text("Swipe"),
value: 'swipe',
groupValue: _view,
onChanged: null),
value: 'swipe'),
],
onSelected: (String viewType) {
_view = viewType;
}));
Use RadioListTile, ignore PopupMenu
Second attempt is to ignore the PopupMenu entirely and just use RadioListTile onChanged. The buttons are not grayed-out/disabled, but are also not functional.
new PopupMenuButton<String>(
...
itemBuilder: (ctx) => <PopupMenuEntry<Null>>[
new PopupMenuItem(
child: new RadioListTile(
title: new Text("Cards"),
value: 'cards',
groupValue: _view,
onChanged: (v) => setState(() => _view = v)),
value: 'cards'),
new PopupMenuItem(
child: new RadioListTile(
title: new Text("Swipe"),
value: 'swipe',
groupValue: _view,
onChanged: (v) => setState(() => _view = v)),
value: 'swipe'),
],
));
What's the correct approach? PopupMenu works well with extremely simple menus, but the element selection is giving me conflicts. Is there a way to get a "dumb" popup menu that displays a column of widgets (styled like a menu) at the button?
I think the best solution for you would be to use CheckedPopupMenuItems instead of a radio list. The functionality should be exactly what you want to achieve, isn't it?
Here is a small example:
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _selectedView = 'Card';
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('TestProject'),
actions: <Widget>[
new PopupMenuButton(
onSelected: (value) => setState(() => _selectedView = value),
itemBuilder: (_) => [
new CheckedPopupMenuItem(
checked: _selectedView == 'Card',
value: 'Card',
child: new Text('Card'),
),
new CheckedPopupMenuItem(
checked: _selectedView == 'Swipe',
value: 'Swipe',
child: new Text('Swipe'),
),
new CheckedPopupMenuItem(
checked: _selectedView == 'List',
value: 'List',
child: new Text('List'),
),
],
),
],
),
body: new Center(child: new Text(_selectedView)),
);
}
}
The problem is that the PopupMenuButton is maintaining the popup dialog as private state (it even pushes a new route onto the Navigator stack). Calling setState won't rebuild the items. You can use an AnimatedBuilder and a ValueNotifier to get around this.
Here's an example of a working radio button list inside a popup:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
State createState() => new MyHomePageState();
}
enum Fruit {
apple,
banana,
}
class MyHomePageState extends State<MyHomePage> {
ValueNotifier<Fruit> _selectedItem = new ValueNotifier<Fruit>(Fruit.apple);
#override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new PopupMenuButton<Fruit>(
itemBuilder: (BuildContext context) {
return new List<PopupMenuEntry<Fruit>>.generate(
Fruit.values.length,
(int index) {
return new PopupMenuItem(
value: Fruit.values[index],
child: new AnimatedBuilder(
child: new Text(Fruit.values[index].toString()),
animation: _selectedItem,
builder: (BuildContext context, Widget child) {
return new RadioListTile<Fruit>(
value: Fruit.values[index],
groupValue: _selectedItem.value,
title: child,
onChanged: (Fruit value) {
_selectedItem.value = value;
},
);
},
),
);
},
);
},
),
),
);
}
}