Skip to content

Instantly share code, notes, and snippets.

@drkdelaney
Created July 19, 2024 21:17
Show Gist options
  • Save drkdelaney/9dcacd88ca498d23bf13c927c636aa12 to your computer and use it in GitHub Desktop.
Save drkdelaney/9dcacd88ca498d23bf13c927c636aa12 to your computer and use it in GitHub Desktop.
Dialog example for returning data from the dialog.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
ThemeMode themeMode = ThemeMode.light;
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
themeMode: themeMode,
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
home: DialogExample(
onThemeModeChange: (ThemeMode mode) {
setState(() {
themeMode = mode;
});
},
),
);
}
}
class DialogExample extends StatelessWidget {
const DialogExample({super.key, required this.onThemeModeChange});
final Function(ThemeMode mode) onThemeModeChange;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FilledButton(
onPressed: () => _dialogBuilder(context),
child: const Text('Set theme mode!'),
),
),
);
}
Future<void> _dialogBuilder(BuildContext context) async {
final result = await showDialog<ThemeMode>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Text('What mode do you want to set?'),
actions: [
TextButton(
onPressed: () {
/// return the false value in the pop
Navigator.of(context).pop(ThemeMode.light);
},
child: Text('Light'),
),
TextButton(
onPressed: () {
/// return the true value in the pop
Navigator.of(context).pop(ThemeMode.dark);
},
child: Text('Dark'),
)
],
);
},
);
if (result != null) {
onThemeModeChange(result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment