Created
July 19, 2024 21:17
-
-
Save drkdelaney/9dcacd88ca498d23bf13c927c636aa12 to your computer and use it in GitHub Desktop.
Dialog example for returning data from the dialog.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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