본문 바로가기

Flutter

Dark & Light Mode with Provider

class LightDarkMode extends StatelessWidget {
  const LightDarkMode({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: Provider.of<ThemeProvider>(context).themeData,
      home: const LDHome(),
    );
  }
}

class LDHome extends StatefulWidget {
  const LDHome({super.key});

  @override
  State<LDHome> createState() => _LDHomeState();
}

class _LDHomeState extends State<LDHome> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: const ADrawer(),
      appBar: AppBar(title: Text('theme button')),
      backgroundColor: Theme.of(context).colorScheme.background,
      body: Center(
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: [
            Container(
              width: 200,
              height: 200,
              color: Theme.of(context).colorScheme.primary,
            ),
            SizedBox(
              width: 100,
              height: 100,
              child: MaterialButton(
                color: Theme.of(context).colorScheme.secondary,
                onPressed: () {
                  Provider.of<ThemeProvider>(context, listen: false).toggleTheme();
                },
                child: Text(Provider.of<ThemeProvider>(context).themeData == lightMode ? 'Light\nMode':'Dark\nMode'
                ,style: TextStyle(fontSize: 20)),
              ),
            )
          ],
        ),
      ),
    );
  }
}

 

Theme
ThemeData lightMode = ThemeData(
  brightness: Brightness.light,
  colorScheme: ColorScheme.light(
    background: Colors.grey.shade400,
    primary: Colors.grey.shade300,
    secondary: Colors.grey.shade200,
  ),
);

ThemeData darkMode = ThemeData(
  brightness: Brightness.dark,
  colorScheme: ColorScheme.dark(
    background: Colors.grey.shade900,
    primary: Colors.grey.shade800,
    secondary: Colors.grey.shade700,
  ),
);

 

Provider
import 'package:flutter/material.dart';

import 'theme.dart';

class ThemeProvider with ChangeNotifier {
  ThemeData _themeData = lightMode;
  ThemeData get themeData => _themeData;

  set themeData(ThemeData themeData) {
    _themeData = themeData;
    notifyListeners();
  }

  void toggleTheme() {
    if (_themeData == lightMode) {
      themeData = darkMode;
    } else {
      themeData = lightMode;
    }
  }
}