Skip to content

Instantly share code, notes, and snippets.

@vsomayaji
Created September 1, 2022 18:05
Show Gist options
  • Save vsomayaji/e71c133f4f50acd77cc2093e8b00121c to your computer and use it in GitHub Desktop.
Save vsomayaji/e71c133f4f50acd77cc2093e8b00121c to your computer and use it in GitHub Desktop.
PopupMenu in AppBar
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
// Auto-enable accessibility for our Blind and Low Vision customers.
RendererBinding.instance.setSemanticsEnabled(true);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
final String _title = 'PopupMenu in AppBar';
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
actions: const <Widget>[
ProfileSwitcher(),
],
title: Text(_title),
),
body: Container(),
),
title: _title,
);
}
}
enum AccountType { business, personal }
class Profile {
final int accountId;
final String accountName;
final AccountType accountType;
const Profile({
required this.accountId,
required this.accountName,
required this.accountType,
});
}
class ProfileSwitcher extends StatefulWidget {
const ProfileSwitcher({Key? key}) : super(key: key);
@override
State<ProfileSwitcher> createState() => _ProfileSwitcherState();
}
class _ProfileSwitcherState extends State<ProfileSwitcher> {
final List<Profile> _profiles = [
const Profile(accountId: 1, accountName: 'Amy Jo', accountType: AccountType.personal),
const Profile(accountId: 2, accountName: 'Amazon', accountType: AccountType.business),
];
late int _selectedAccountId;
@override
void initState() {
super.initState();
_selectedAccountId = _profiles.first.accountId;
}
@override
Widget build(BuildContext context) {
return PopupMenuButton(
color: Colors.grey,
initialValue: _selectedAccountId,
itemBuilder: (BuildContext context) {
return _profiles
.map((p) => PopupMenuItem<int>(
value: p.accountId,
child: ProfileSwitcherItem(profile: p),
))
.toList(growable: false);
},
onSelected: (int newValue) => setState(() => _selectedAccountId = newValue),
tooltip: 'Profile',
child: Padding(
padding: const EdgeInsets.only(right: 10), // Don't hug the wall.
child: ProfileSwitcherItem(profile: _profiles.firstWhere((p) => p.accountId == _selectedAccountId)),
),
);
}
}
class ProfileSwitcherItem extends StatelessWidget {
final Profile profile;
const ProfileSwitcherItem({
required this.profile,
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Icon(profile.accountType == AccountType.business ? Icons.work : Icons.account_circle),
const SizedBox(width: 5),
Text('${profile.accountName} - ${profile.accountType == AccountType.business ? 'Business' : 'Personal'}')
],
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment