I am looking to keep the selected item from a DropdownButton list as the text in that button. Right now, I can click on the item in the dropdown list and I am showing a snackbar notification with the item selected, but it is not updating the actual dropdownbutton's text. What am I missing?
Here is my code:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class InfoScreen extends StatefulWidget {
const InfoScreen({Key? key}) : super(key: key);
@override
State<InfoScreen> createState() => _InfoScreenState();
}
class _InfoScreenState extends State<InfoScreen> {
String selectedFaction = '';
@override
void initState() {
// TODO: implement initState
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
onPressed: () {},
icon: const Icon(Icons.person_sharp),
),
elevation: 5,
centerTitle: true,
titleSpacing: 0,
title: const Text('Info Screen'),
actions: <Widget>[
IconButton(
onPressed: () {},
icon: const Icon(Icons.settings),
),
],
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Center(
child: Column(
children: [
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("factions")
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData) {
final factionDatabaseSnapshot = snapshot.data!.docs;
factionDatabaseSnapshot.sort(
((a, b) {
return a['name']
.toLowerCase()
.compareTo(b['name'].toLowerCase());
}),
);
return DropdownButton(
onChanged: (snap) {
setState(() {
selectedFaction = snap.toString();
});
final snackbarFaction = SnackBar(
content: Text('Faction Selected: $selectedFaction'),
);
ScaffoldMessenger.of(context)
.showSnackBar(snackbarFaction);
},
items: factionDatabaseSnapshot
.map((DocumentSnapshot document) {
return DropdownMenuItem<String>(
value: document['name'],
child: Text(document['name']),
);
}).toList(),
isExpanded: false,
isDense: false,
hint: const Text('Select a faction'),
);
} else {
return const CircularProgressIndicator();
}
},
),
],
),
),
),
);
}
}
Screenshot of what I am seeing
I'd also like to save this item into Firestore on a 'submit' button, but I haven't gotten that far yet.
Any help would be greatly appreciated!
Update: Error I am receiving after adding the code from the answer selected below
CodePudding user response:
your code is fine you just need to add value property inside dropdown -
return DropdownButton(
value: selectedFaction,
onChanged: (snap) {
setState(() {
selectedFaction = snap.toString();
});
final snackbarFaction = SnackBar(
content: Text('Faction Selected: $selectedFaction'),
);
ScaffoldMessenger.of(context)
.showSnackBar(snackbarFaction);
},