Home > Software design >  When the System Dark Mode is Enabled Color Doesn't Change in Flutter
When the System Dark Mode is Enabled Color Doesn't Change in Flutter

Time:11-05

When the system dark mode is enabled color doesn't change. How to change color when the system dark mode is enabled or disabled? When the switch changes color changes. But when the system dark mode changes color doesn't change. I am using shared_preferences library. I want to change color when the switch changes and when the system dark mode changes.

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

void main() {
  runApp(MainApp());
}

class MainApp extends StatefulWidget {
  MainApp({super.key});

  @override
  State<MainApp> createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  bool isSwitched = false;

  Future<bool> saveSwitchState(bool value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setBool("switchState", value);
  }

  Future<bool> getSwitchState() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool isSwitched = prefs.getBool("switchState") ?? false;
    return isSwitched;
  }

  getSwitchValues() async {
    isSwitched = await getSwitchState();
    setState(() {});
  }

  isDarkMode() {
    var brightness = MediaQuery.of(context).platformBrightness;
    bool isDarkMode = brightness == Brightness.dark;
    if (isDarkMode) {
      setState(() {
        isSwitched = true;
        saveSwitchState(true);
      });
    } else {
      setState(() {
        isSwitched = false;
        saveSwitchState(false);
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getSwitchValues();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
            child: Column(
          children: [
            Switch(
              value: isSwitched,
              onChanged: (bool value) {
                setState(() {
                  isSwitched = value;
                  saveSwitchState(value);
                });
              },
            ),
            Expanded(
              child: Container(
                color: isSwitched ? Colors.black : Colors.white,
              ),
            ),
          ],
        )),
      ),
    );
  }
}

CodePudding user response:

You have defined isDarkMode but you are not calling this function inside build method. That should be the reason this is not working. Try calling it.

Better method would be to define themes for both dark and light mode and use themeMode inside the material app.

themeMode: ThemeMode.system

  • Related