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.

Revisions

  1. drkdelaney created this gist Jul 19, 2024.
    80 changes: 80 additions & 0 deletions change_theme_dialog.dart
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,80 @@
    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);
    }
    }
    }