MartinCo
MartinCo

Reputation: 127

How can I set Dark mode theme in Flutter

I have already mad a program that does that but it wont refresh after I change the value...I am also having trouble setting the the values in different classes.

My main.dart:

import 'package:flutter/material.dart';
import 'drawer.dart';
import 'settings.dart';

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

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);
  bool darkMode = false;
  var mainTheme = ThemeData.light();

  @override
  Widget build(BuildContext context) {
    if (MyApp().darkMode == true) {
      mainTheme = ThemeData.dark();
    }
    return MaterialApp(
      home: _MyApp(),
      theme: mainTheme,
    );
  }
}

class _MyApp extends StatefulWidget {
  const _MyApp({Key? key}) : super(key: key);

  @override
  State<_MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<_MyApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Jawsa"),
      ),
      body: Row(
        children: [
          Expanded(
              child: ListTile(
            leading: Text(MyApp().darkMode.toString()),
          ))
        ],
      ),
      drawer: MyDrawer(),
    );
  }
}

My Drawer:

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

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

class MyDrawer extends StatelessWidget {
  const MyDrawer({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: ListView(
        children: [
          ListTile(
              leading: Icon(Icons.settings),
              title: Text("Settings"),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => const Settings()),
                );
              }),
        ],
      ),
    );
  }
}

My Settings:

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

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

class Settings extends StatelessWidget {
  const Settings({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Settings"),
      ),
      body: const _Settings(),
    );
  }
}

class _Settings extends StatefulWidget {
  const _Settings({Key? key}) : super(key: key);

  @override
  State<_Settings> createState() => _SettingsState();
}

class _SettingsState extends State<_Settings> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: ListView(
            children: [
              ListTile(
                leading: Icon(Icons.dark_mode, size: 35),
                title: Text("Dark Mode"),
                subtitle: Text("Here you can change you're theme."),
                trailing: Switch(
                  value: MyApp().darkMode,
                  activeTrackColor: Color.fromARGB(255, 89, 216, 255),
                  activeColor: Color.fromARGB(255, 78, 76, 175),
                  onChanged: (value) {
                    setState(() {
                      MyApp().darkMode = value;
                    });
                  },
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}

I have a variable MyApp().darkMode and im trying to change it with the Switch() for false to true. The code worked when the variable was set to static bool darkMode = false; in the main file. But the mode didn't refresh until I manually did a Hot reload. And only after that did the Theme change from light to dark and vice versa.

Anyone have any ideas to how i can change fix this problem?

P.S. Im trying not to use any other extensions/dependencies

Upvotes: 1

Views: 4649

Answers (1)

Samuel Olufemi
Samuel Olufemi

Reputation: 905

By using the provider package: https://pub.dev/packages/provider I made changes to your main.dart and setting.dart file and switching between modes works.

main.dart:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'drawer.dart';

void main() {
  runApp(
      ChangeNotifierProvider(create: (context) => DarkMode(), child: MyApp()));
}

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);
  var mainTheme = ThemeData.light();
  var darkTheme = ThemeData.dark();


  @override
  Widget build(BuildContext context) {

    final themeMode = Provider.of<DarkMode>(context);


    return MaterialApp(
      home: const _MyApp(),
      theme: themeMode.darkMode ? darkTheme : mainTheme,
    );
  }
}

class _MyApp extends StatefulWidget {
  const _MyApp({Key? key}) : super(key: key);

  @override
  State<_MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<_MyApp> {
  @override
  Widget build(BuildContext context) {
    final themeMode = Provider.of<DarkMode>(context);
    return Scaffold(
      appBar: AppBar(
        title: const Text("Jawsa"),
      ),
      body: Row(
        children: [
          Expanded(
              child: ListTile(
                leading: Text(themeMode.darkMode.toString()),
              ))
        ],
      ),
      drawer: const MyDrawer(),
    );
  }
}


class DarkMode with ChangeNotifier {
  bool darkMode = true; ///by default it is true
  ///made a method which will execute while switching
  changeMode() {
    darkMode = !darkMode;
    notifyListeners(); ///notify the value or update the widget value
  }
}

settings.dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'main.dart';



class Settings extends StatelessWidget {
  const Settings({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Settings"),
      ),
      body: const _Settings(),
    );
  }
}

class _Settings extends StatefulWidget {
  const _Settings({Key? key}) : super(key: key);

  @override
  State<_Settings> createState() => _SettingsState();
}

class _SettingsState extends State<_Settings> {
  @override
  Widget build(BuildContext context) {
    final themeMode = Provider.of<DarkMode>(context);
    return Column(
      children: [
        Expanded(
          child: ListView(
            children: [
              ListTile(
                leading: const Icon(Icons.dark_mode, size: 35),
                title: const Text("Dark Mode"),
                subtitle: const Text("Here you can change you're theme."),
                trailing: Switch(
                  value: themeMode.darkMode,
                  activeTrackColor: const Color.fromARGB(255, 89, 216, 255),
                  activeColor: const Color.fromARGB(255, 78, 76, 175),
                  onChanged: (value) {
                    themeMode.changeMode();
                  },
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}

Upvotes: 3

Related Questions