'How do I change self-made themes of my app in Flutter in real time

I have my own made dark theme in my current app. Now, I also want to add light theme to it. I have seen some answers, but I have a condition that, my MaterialApp is already inside a ChangeNotifierProvider for API Data. Now, as I saw in some examples, I need another change notifierprovider for changing theme real time. Also, my theme button is on another page, far away from main. So, how should I implement this functionality.

Here is my MyApp -

return ChangeNotifierProvider(
      create: (context) => APIData(),
      child: MaterialApp(
        title: 'Testing',
        theme: ThemeData(
          fontFamily: 'Nunito Sans',
          brightness: Brightness.dark,
          textTheme: TextTheme(
            headline1: headingStyle1,
            headline2: headingStyle2,
            headline3: headingStyle3,
            headline4: headingStyle4,
            headline6: bodyText3,
            bodyText1: bodyText1,
            bodyText2: bodyText2,
            button: buttonTextStyle,
            caption: linkStyle,
          ),
        ),
        //themeMode: _themeMode,
        // home: SplashScreen(),
        initialRoute: isViewed==0 || isViewed==null ? 'splash' : 'home',
        navigatorObservers: <NavigatorObserver>[observer],
        routes: {
          'home': (context) => AuthenticationWrapper(),
          'splash' : (context) => SplashScreen(),
        },
        scaffoldMessengerKey: scaffoldMessengerKey,
        navigatorKey: navigatorKey,
      ),
    );

theme_manager.dart -

import 'package:flutter/material.dart';

import '../styles.dart';
import 'storage_manager.dart';

class ThemeNotifier with ChangeNotifier {
  final darkTheme = ThemeData(
    fontFamily: 'Nunito Sans',
    brightness: Brightness.dark,
    textTheme: TextTheme(
      headline1: headingStyle1,
      headline2: headingStyle2,
      headline3: headingStyle3,
      headline4: headingStyle4,
      headline6: bodyText3,
      bodyText1: bodyText1,
      bodyText2: bodyText2,
      button: buttonTextStyle,
      caption: linkStyle,
    ),
  );

  final lightTheme = ThemeData(
    primarySwatch: Colors.grey,
    primaryColor: Colors.white,
    brightness: Brightness.light,
    backgroundColor: const Color(0xFFE5E5E5),
    accentColor: Colors.black,
    accentIconTheme: IconThemeData(color: Colors.white),
    dividerColor: Colors.white54,
  );

  ThemeData _themeData = ThemeData.light();
  ThemeData getTheme() => _themeData;

  ThemeNotifier() {
    StorageManager.readData('themeMode').then((value) {
      print('value read from storage: ' + value.toString());
      var themeMode = value ?? 'light';
      if (themeMode == 'light') {
        _themeData = lightTheme;
      } else {
        print('setting dark theme');
        _themeData = darkTheme;
      }
      notifyListeners();
    });
  }

  void setDarkMode() async {
    _themeData = darkTheme;
    StorageManager.saveData('themeMode', 'dark');
    notifyListeners();
  }

  void setLightMode() async {
    _themeData = lightTheme;
    StorageManager.saveData('themeMode', 'light');
    notifyListeners();
  }
}

storage_manager.dart -

import 'package:shared_preferences/shared_preferences.dart';

class StorageManager {
  static void saveData(String key, dynamic value) async {
    final prefs = await SharedPreferences.getInstance();
    if (value is int) {
      prefs.setInt(key, value);
    } else if (value is String) {
      prefs.setString(key, value);
    } else if (value is bool) {
      prefs.setBool(key, value);
    } else {
      print("Invalid Type");
    }
  }

  static Future<dynamic> readData(String key) async {
    final prefs = await SharedPreferences.getInstance();
    dynamic obj = prefs.get(key);
    return obj;
  }

  static Future<bool> deleteData(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.remove(key);
  }
}

And, from here I have to change my theme, which is in settings.dart, which is navigated after at least 3-4 pages -

                          CustomSwitch1(
                                value: status,
                                onChanged: (bool val) {
                                  setState(() {
                                    status = val;
                                    print(status);

                                  });
                                },
                              ),


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source