Flutter DropdownButtonFormField setState does not work outside of onChanged method - flutter

I just created a simple flutter app with two DropdownButtonFormField widgets.
And I want to update both widgets if first one is selected.
Expectation:
select number from the first dropdown menu
same number appears in the second dropdown
Result:
- select number from the first dropdown menu
- only the first dropdown menu is updated
Can somebody please tell me what I am doing wrong when calling setState onChaged method of the first dropdown menu widget?
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
List<int> myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
int currentNumber = 1;
int anotherNumber = 9;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
DropdownButtonFormField<int>(
value: currentNumber,
items: myList.map((int value) {
return DropdownMenuItem<int>(
value: value,
child: Container(
width: 200,
child: Text(
value.toString(),
),
),
);
}).toList(),
onChanged: (int newValue) {
setState(() {
currentNumber = newValue;
anotherNumber = newValue;
});
},
),
DropdownButtonFormField<int>(
value: anotherNumber,
items: myList.map((int value) {
return DropdownMenuItem<int>(
value: value,
child: Container(
width: 200,
child: Text(
value.toString(),
),
),
);
}).toList(),
onChanged: (int newValue) {
setState(() {
anotherNumber = newValue;
});
},
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}}

Related

Flutter: Dismissible in PopupMenuButton does not risize while displayed

I want to use a Dismissible Widget in a PopupMenuButton to delete items in the popup list.
My example code (see the example main() code below) works for deleting an item (String) in the PopupMenuButton, but the list is not refreshed and resized letting a blank space in the list while the popup is still displayed.
The list is only displayed resized after the popup is closed and then reopened.
I remove the item from the list in a setState in the onDismissed callback so the widget tree should be rebuild.
How can I update and resize the displayed list in the popup without having to close and reopen it?
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter PopupMenuButton sample',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String dropdownValue = 'Orange';
final _items = [
'Orange',
'Banana',
'Grapes',
'Apple',
'watermelon',
'Pineapple'
];
#override
Widget build(BuildContext context) {
print("build Scaffold");
return Scaffold(
appBar: AppBar(
title: Text("DropDownList Example"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("$dropdownValue"),
const Spacer(),
PopupMenuButton<String>(
icon: Icon(Icons.bookmarks_outlined),
onSelected: (String value) {
setState(() {
dropdownValue = value;
});
print(value);
},
itemBuilder: (BuildContext context) {
return _items.map<PopupMenuItem<String>>((String _value) {
return PopupMenuItem(
value: _value,
child: Dismissible(
key: UniqueKey(),
direction: DismissDirection.endToStart,
onDismissed: (i) {
print("onDismissed $_value");
setState(() {
_items.remove(_value);
});
},
child: ListTile(
title: Text(_value),
trailing: const Icon(Icons.arrow_back),
),
background: Container(
color: Colors.red,
margin: const EdgeInsets.symmetric(horizontal: 15),
alignment: Alignment.centerRight,
child: const Icon(
Icons.delete,
color: Colors.white,
),
),
),
);
}).toList();
},
),
const Spacer(
flex: 10,
),
],
),
),
);
}
}

DropdownButton doesn't re-render the menu when items change

DropdownButton doesn't reflect menuItem's changes when the dropdown menu is open.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: Center(
child: MyStatefulWidget(),
),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
#override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
final disabledItems = ['Free', 'Four'];
List<String> items = ['One', 'Two', 'Free', 'Four'];
String dropdownValue = 'One';
#override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: dropdownValue,
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String newValue) {
if (!disabledItems.contains(newValue)) {
setState(() {
dropdownValue = newValue;
});
}
},
items: items.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Row(children: [
Text(
value,
style: TextStyle(
color: disabledItems.contains(value) ? Colors.grey : null,
),
),
IconButton(
icon: Icon(Icons.delete),
color: Colors.black38,
onPressed: () {
setState(() {
items.removeWhere((element) => element == 'Two');
});
print(items.length);
},
)
]),
);
}).toList(),
);
}
}
What I aim is the chance of removing an item from the menu when the delete icon is pressed. All the expected events are working as expected and the DropDown items list is updating accordingly in the backend but it doesn't re-render.
DorpDown Menu with delete icon
In order to be able to see the updated items list I have to close the dropdown menu and open it again but this doesn’t feel right in terms of user experience.

TypeAhead different widgets flutter

I'm trying to create different widgets in TypeAhead suggestion depends on suggestion.subName.length
1. ListTile with a subTitle
2. ListTile without subTitle
TypeAhead(
...
itemBuilder: (context, suggestion) {
return ListTile(
dense: true,
title: AutoSizeText(
suggestion.primeName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
minFontSize: 20,
),
subtitle: suggestion.subName.length == 0 ? null:AutoSizeText(
suggestion.subName.join(', '),
maxLines: 1,
overflow: TextOverflow.ellipsis,
minFontSize: 15,
),
);
},
...
But everything comes back with a subtitle.
What could cause that? Is it possible to make 2 different types of widgets in TypeAhead?
You can copy paste run full code below
I use the following example to simulate this case
You can return Container() not null
subtitle: suggestion.subName.length == 0 ? Container() : AutoSizeText(
or put condition in itemBuilder, for more complex condition you can use if
itemBuilder: (context, suggestion) {
return suggestion.subName.length == 0 ? ListTile(...) : ListTile(...);
working demo
full code
import 'package:flutter/material.dart';
import 'dart:math';
import 'package:flutter_typeahead/flutter_typeahead.dart';
class BackendService {
static Future<List> getSuggestions(String query) async {
await Future.delayed(Duration(seconds: 1));
return List.generate(3, (index) {
return {'name': query + index.toString(), 'price': Random().nextInt(100)};
});
}
}
class CitiesService {
static final List<String> cities = [
'Beirut',
'Damascus',
'San Fransisco',
'Rome',
'Los Angeles',
'Madrid',
'Bali',
'Barcelona',
'Paris',
'Bucharest',
'New York City',
'Philadelphia',
'Sydney',
];
static List<String> getSuggestions(String query) {
List<String> matches = List();
matches.addAll(cities);
matches.retainWhere((s) => s.toLowerCase().contains(query.toLowerCase()));
return matches;
}
}
class NavigationExample extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(32.0),
child: Column(
children: <Widget>[
SizedBox(
height: 10.0,
),
TypeAheadField(
textFieldConfiguration: TextFieldConfiguration(
autofocus: true,
style: DefaultTextStyle.of(context)
.style
.copyWith(fontStyle: FontStyle.italic),
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'What are you looking for?'),
),
suggestionsCallback: (pattern) async {
return await BackendService.getSuggestions(pattern);
},
itemBuilder: (context, suggestion) {
return ListTile(
leading: Icon(Icons.shopping_cart),
title: Text(suggestion['name']),
subtitle: suggestion['price'] < 20
? Container()
: Text('\$${suggestion['price']}'),
);
},
onSuggestionSelected: (suggestion) {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => ProductPage(product: suggestion)));
},
),
],
),
);
}
}
class ProductPage extends StatelessWidget {
final Map<String, dynamic> product;
ProductPage({this.product});
#override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(50.0),
child: Column(
children: [
Text(
this.product['name'],
style: Theme.of(context).textTheme.headline,
),
Text(
this.product['price'].toString() + ' USD',
style: Theme.of(context).textTheme.subhead,
)
],
),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
NavigationExample(),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

In flutter, can you set the appbar backgorund to change base on the value of a dropdown box?

my drop down box cycles through 5 strings
['blue','red','yellow','orange','grey']
I want my appbar title to be that dropdown box and for the value in the dropdown to determine the appbar color
DropDownWidget ddw = DropDownWidget();
var color = {
"blue": Colors.blue,
"red": Colors.red,
"yellow": Colors.yellow,
"orange": Colors.orange,
"grey": Colors.grey,
};
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: ddw,
backgroundColor: color[ddw],
),
}
The dropdown (ddw) shows up as the title, no problem.
I made a dictionary with those strings as the keys and the corresponding color as the value, but I am not able to use the string value of the dropdown to change the background.
Any suggestions?
You can copy paste run full code below
You can call setState in onChanged of DropdownButton
code snippet
appBar: AppBar(
backgroundColor: _appbarColor,
...
DropdownButton<Item>(
hint: Text("Select item"),
value: selectedColor,
onChanged: (Item Value) {
setState(() {
selectedColor = Value;
_appbarColor = selectedColor.color;
});
},
working demo
full code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class Item {
const Item(this.name, this.color);
final String name;
final Color color;
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
Color _appbarColor = Colors.blue;
Item selectedColor;
List<Item> colorList = <Item>[
const Item('blue', Colors.blue),
const Item('red', Colors.red),
const Item('yellow', Colors.yellow),
];
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: _appbarColor,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButton<Item>(
hint: Text("Select item"),
value: selectedColor,
onChanged: (Item Value) {
setState(() {
selectedColor = Value;
_appbarColor = selectedColor.color;
});
},
items: colorList.map((Item item) {
return DropdownMenuItem<Item>(
value: item,
child: Row(
children: <Widget>[
Container(
height: 15,
width: 15,
color: item.color,
),
SizedBox(
width: 10,
),
Text(
item.name,
style: TextStyle(color: Colors.black),
),
],
),
);
}).toList()),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

How do I clear a Flutter DropdownButton programmatically?

I have two dropdown buttons that are mutually exclusive. How can I clear (or set) the value of one when the other is set?
Thanks
for 1st dropdown:
onChanged: (String newValue) {
setState(() {
dropdownValueFirst = newValue;
dropdownValueSecond = "Bangladesh";
});
},
for 2nd dropdown:
onChanged: (String newValue) {
setState(() {
dropdownValueSecond = newValue;
dropdownValueFirst ="One";
});
},
See below code:
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
String dropdownValueFirst="One";
String dropdownValueSecond="Bangladesh";
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButton<String>(
value: dropdownValueFirst,
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(
color: Colors.deepPurple
),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String newValue) {
setState(() {
dropdownValueFirst = newValue;
dropdownValueSecond = "Bangladesh";
});
},
items: <String>['One', 'Two', 'Free', 'Four']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
})
.toList(),
),
const Padding(padding: EdgeInsets.only(left: 8)),
DropdownButton<String>(
value: dropdownValueSecond,
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(
color: Colors.deepPurple
),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String newValue) {
setState(() {
dropdownValueSecond = newValue;
dropdownValueFirst ="One";
});
},
items: <String>['Bangladesh', 'India', 'China']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
})
.toList(),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
When 1st drop down in pressed then try to reset value of 2nd dropdown inside setState on onChanged event and vice versa,
onChanged: (String newValue) {
setState(() {
dropdownValueFirst = newValue;
dropdownValueSecond='Initial Value of second',// remeber this value must be same as initial value of 2nd dropdown =>value: 'Initial Value of second',
});
},