Flutter: How to map a list of maps? - flutter

I have a very simple list of maps.
List<Map<String, String>> items = [
{ 'a': 'Some Text' },
{ 'b': 'Another Text' },
];
I want to map the above list to a dropdown list.
DropdownButton<String>(
hint: Text('Select a value'),
items: items.map((item) {
return DropdownMenuItem<String>(
value: // how to get key here a, b
child: // how to get value 'Some Text', 'Another Text'
);
}).toList(),
onChanged: (String newValue) {
setState(() {
// ...
});
},
),
)
How to get the key of the map, item has a property keys but not key and values and not value.

For this particular input:
List<Map<String, String>> items = [
{ 'a': 'Some Text' },
{ 'b': 'Another Text' },
];
You can do a workaround by accessing all the keys/values using getters and locating its very first element like this.
DropdownButton<String>(
items: items.map((item) {
return DropdownMenuItem<String>(
value: item.keys.first,
child: Text(item.values.first),
);
}).toList(),
onChanged: (value){},
)

You can copy paste run full code below
You need to use DropdownButton<Map<String, String>>
You can adjust Text("${value.keys.first} ${value.values.first}") per your request
code snippet
DropdownButton<Map<String, 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: (Map<String, String> newValue) {
setState(() {
dropdownValue = newValue;
print(
"${dropdownValue.keys.first} ${dropdownValue.values.first}");
});
},
items: items.map<DropdownMenuItem<Map<String, String>>>(
(Map<String, String> value) {
return DropdownMenuItem<Map<String, String>>(
value: value,
child: Text("${value.keys.first} ${value.values.first}"),
);
}).toList(),
),
working demo
full code
import 'package:flutter/material.dart';
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> {
List<Map<String, String>> items = [
{'a': 'Some Text'},
{'b': 'Another Text'},
];
Map<String, String> dropdownValue;
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>[
DropdownButton<Map<String, 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: (Map<String, String> newValue) {
setState(() {
dropdownValue = newValue;
print(
"${dropdownValue.keys.first} ${dropdownValue.values.first}");
});
},
items: items.map<DropdownMenuItem<Map<String, String>>>(
(Map<String, String> value) {
return DropdownMenuItem<Map<String, String>>(
value: value,
child: Text("${value.keys.first} ${value.values.first}"),
);
}).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),
),
);
}
}

Related

How to put "RadioButton" or any kind of menu item list inside an "ExpansionPanelList"?

I am looking to create something like the following pic:
But it seems there is no proper example or tutorial on the internet, so I ask here.
I have the following code for simple ExpansionPanelList:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
// Remove the debug banner
debugShowCheckedModeBanner: false,
title: 'Epnasion Radio',
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: const HomePage());
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
// Generating some dummy data
final List<Map<String, dynamic>> _items = List.generate(
20,
(index) => {
'id': index,
'title': 'Item $index',
'description':
'This is the description of the item $index. There is nothing important here. In fact, it is meaningless.',
'isExpanded': false
});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Expansion List'),
),
body: SingleChildScrollView(
child: ExpansionPanelList(
elevation: 3,
// Controlling the expansion behavior
expansionCallback: (index, isExpanded) {
setState(() {
_items[index]['isExpanded'] = !isExpanded;
});
},
animationDuration: const Duration(milliseconds: 600),
children: _items
.map(
(item) => ExpansionPanel(
canTapOnHeader: true,
backgroundColor:
item['isExpanded'] == true ? Colors.grey : Colors.white,
headerBuilder: (_, isExpanded) => Container(
padding: const EdgeInsets.symmetric(
vertical: 15, horizontal: 30),
child: Text(
item['title'],
style: const TextStyle(fontSize: 20),
)),
body: Container(
padding: const EdgeInsets.symmetric(
vertical: 15, horizontal: 30),
child: Text(item['description']),
),
isExpanded: item['isExpanded'],
),
)
.toList(),
),
),
);
}
}
This should work for you
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: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({
Key? key,
required this.title,
}) : super(key: key);
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> chapterAAnswers = ["A","B"];
List<String> chapterBAnswers = ["A","B","C","D"];
late String selectedAnswerChapterA;
late String selectedAnswerChapterB;
#override
void initState() {
selectedAnswerChapterA = chapterAAnswers[0];
selectedAnswerChapterB = chapterBAnswers[0];
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children: <Widget>[
ExpansionTile(
title: Text('Chapter A'),
children: <Widget>[
RadioListTile<String>(
title: const Text('A'),
value: chapterAAnswers[0],
groupValue: selectedAnswerChapterA,
onChanged: (String? value) {
setState(() {
selectedAnswerChapterA = value!;
});
},
),
RadioListTile<String>(
title: const Text('B'),
value: chapterAAnswers[1],
groupValue: selectedAnswerChapterA,
onChanged: (String? value) {
setState(() {
selectedAnswerChapterA = value!;
});
},
),
],
),
ExpansionTile(
title: Text('Chapter B'),
children: <Widget>[
RadioListTile<String>(
title: const Text('A'),
value: chapterBAnswers[0],
groupValue: selectedAnswerChapterB,
onChanged: (String? value) {
setState(() {
selectedAnswerChapterB = value!;
});
},
),
RadioListTile<String>(
title: const Text('B'),
value: chapterBAnswers[1],
groupValue: selectedAnswerChapterB,
onChanged: (String? value) {
setState(() {
selectedAnswerChapterB = value!;
});
},
),
RadioListTile<String>(
title: const Text('C'),
value: chapterBAnswers[2],
groupValue: selectedAnswerChapterB,
onChanged: (String? value) {
setState(() {
selectedAnswerChapterB = value!;
});
},
),
RadioListTile<String>(
title: const Text('D'),
value: chapterBAnswers[3],
groupValue: selectedAnswerChapterB,
onChanged: (String? value) {
setState(() {
selectedAnswerChapterB = value!;
});
},
),
],
),
],
),
);
}
}
you can try this, define item:
List<Map<String, dynamic>> _items = List.generate(
10,
(index) => {
'id': index,
'title': 'Item $index',
'description':
'This is the description of the item $index. Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
'isExpanded': false,
'radio': {
'value': [1, 2, 3, 4, 6],
'groupValue': 1
}
});
and then :
SingleChildScrollView(
child: ExpansionPanelList(
elevation: 3,
expansionCallback: (index, isExpanded) {
setState(() {
_items[index]['isExpanded'] = !isExpanded;
});
},
animationDuration: Duration(milliseconds: 600),
children: _items
.map(
(item) => ExpansionPanel(
canTapOnHeader: true,
backgroundColor: item['isExpanded'] == true
? Colors.cyan[100]
: Colors.white,
headerBuilder: (_, isExpanded) => Container(
padding: EdgeInsets.symmetric(vertical: 15, horizontal: 30),
child: Text(
item['title'],
style: TextStyle(fontSize: 20),
)),
body: Container(
padding: EdgeInsets.symmetric(vertical: 15, horizontal: 30),
child: SingleChildScrollView(
child: ListView.builder(
shrinkWrap: true,
itemCount: (item['radio']['value'] as List).length,
itemBuilder: (context, index) {
return RadioListTile(
value: index,
groupValue: item['radio']['groupValue'],
onChanged: (value) {
setState(() {
item['radio']['groupValue'] = value;
});
});
}),
),
),
isExpanded: item['isExpanded'],
),
)
.toList(),
),
)

How to adjust the height and width of a dropdown list in flutter (I've given the code, just tell me how to adjust that)

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> {
String dropdownValue = 'One';
#override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: dropdownValue,
icon: Icon(Icons.arrow_downward),
iconSize: 15,
elevation: 16,
style: TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: <String>['One', 'Two', 'Free', 'Four']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
);
}
}
You can add width: (specification) and height: (specification) in your dropdown list. Specification -> number.
Please, use the Code Sample formatting option.
you can do it like this :
return Container(
child: DropdownButton(
value: dropdownValue,
icon: Icon(Icons.arrow_downward),
iconSize: 15,
elevation: 16,
style: TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: ['One', 'Two', 'Free', 'Four'] .map<DropdownMenuItem>((String value) {
return DropdownMenuItem(
value: value,
child: Container(
height: 100,
width: 200,
alignment: Alignment.centerLeft,
child: Text(value)
)
);
}).toList(),
)
);
Btw, please use the Code Sample formatting option.

String not updating with changeNotifierProvider

model class:
Venue with ChangeNotifier{
String id;
update(String venueId) {
id = venueId;
notifyListeners();
}
}
Trying to get the id value like so:
Widget _buildContents(BuildContext context) {
final venue = Provider.of<Venue>(context);
final id = venue.id;
print('##########'); //// trying to get the the id here.
}
My id is supposed to be updated in the onTap callback of a dropDownButton:
DropdownButton(
....
items: venues.map((venue) {
return DropdownMenuItem<String>(
onTap: () {
venue.update(venue.id);
},
value: venue.name,
child: Text(
venue.name,
style: TextStyle(fontSize: 28),
),
);
}).toList(),
.....
)
And the Provider.. is above the widgets:
MultiProvider(providers: [
ChangeNotifierProvider<Venue>(create: (_) => Venue()),
], child: HomePage());
Something is wrong..help!?
You can copy paste run full code below
You can use DropdownButton<Venue> and call venue.update in onChanged
code snippet
DropdownButton<Venue>(
value: dropdownValue,
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (Venue newValue) {
setState(() {
dropdownValue = newValue;
venue.update(newValue.id);
});
},
items: venues.map((venue) {
return DropdownMenuItem<Venue>(
value: venue,
child: Text(
venue.name,
style: TextStyle(fontSize: 28),
),
);
}).toList()
working demo output
I/flutter (27988): ########## 1
I/flutter (27988): ########## 2
working demo
full code
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Venue with ChangeNotifier {
String id;
String name;
update(String venueId) {
id = venueId;
notifyListeners();
}
Venue({this.id, this.name});
}
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: MultiProvider(providers: [
ChangeNotifierProvider<Venue>(create: (_) => Venue()),
], child: HomePage()),
);
}
}
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Venue dropdownValue;
List<Venue> venues = [
Venue(id: "1", name: "name1"),
Venue(id: "2", name: "name2"),
Venue(id: "3", name: "name3"),
];
#override
Widget build(BuildContext context) {
final venue = Provider.of<Venue>(context);
final id = venue.id;
print('########## $id');
return Scaffold(
appBar: AppBar(
title: Text("demo"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButton<Venue>(
value: dropdownValue,
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (Venue newValue) {
setState(() {
dropdownValue = newValue;
venue.update(newValue.id);
});
},
items: venues.map((venue) {
return DropdownMenuItem<Venue>(
value: venue,
child: Text(
venue.name,
style: TextStyle(fontSize: 28),
),
);
}).toList(),
),
],
),
),
);
}
}

Flutter DropdownButtonFormField setState does not work outside of onChanged method

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),
),
);
}}

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',
});
},