Issue
I want the item I selected from dropDownMenu to be changed by default. How can I do it? The code I wrote is not working.
Code:
import 'package:flutter/material.dart';
import 'package:flutter_emoji/flutter_emoji.dart';
class arayuzEkrani extends StatefulWidget {
@override
State<arayuzEkrani> createState() => _arayuzEkraniState();
}
class _arayuzEkraniState extends State<arayuzEkrani> {
Map countryFlags = {"usa": "🇺🇸", "turkey": "🇹🇷", "italy": "🇮🇹", "germany": "🇩🇪", "france": "🇫🇷", "spain": "🇪🇸"};
var defaultFlag = "🇺🇸";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
leading: Icon(Icons.public, color: Colors.black, size: 27,),
title: Text("Learn words", style: TextStyle(color: Colors.black),),
elevation: 0,
actions: [
DropdownButton(
items: countryFlags.keys.map((country) {
return DropdownMenuItem(
child: Text(countryFlags[country]),
value: defaultFlag,
);
}).toList(),
onChanged: (country) {
setState(() {
defaultFlag = countryFlags[country];
print(country);
});
},
)
],
),
);
}
}
Also coming to the console are:
E/flutter (11954):
E/flutter (11954): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'Null' is not a subtype of type 'String'
E/flutter (11954): #0 _arayuzEkraniState.build.<anonymous closure>.<anonymous closure>
package:kelimeogrenmeuygulamasi/arayuzEkrani.dart:35
E/flutter (11954): #1 State.setState
package:flutter/…/widgets/framework.dart:1088
My goal is to select a country via dropDownButton.
Solution
Check this out i have used your code and created an example for you :
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: MyApp()));
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Map<String, String> countryFlags = {
"usa": "🇺🇸",
"turkey": "🇹🇷",
"italy": "🇮🇹",
"germany": "🇩🇪",
"france": "🇫🇷",
"spain": "🇪🇸"
};
var defaultFlag = "🇺🇸";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
leading: const Icon(
Icons.public,
color: Colors.black,
size: 27,
),
title: const Text(
"Learn words",
style: TextStyle(color: Colors.black),
),
elevation: 0,
actions: [
DropdownButton<String>(
items: countryFlags
.map((country, flag) {
return MapEntry(
country,
DropdownMenuItem<String>(
value: flag,
child: Text(flag),
));
})
.values
.toList(),
value: defaultFlag,
onChanged: (String? country) {
setState(() {
defaultFlag = country!;
});
},
)
],
),
);
}
}
Check out and let me know if it works.
Answered By - Sagar Acharya
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.