1

i am trying to create a way to start my app with system theme and then giving user a switch to choose between light mode and dark mode

in my main.dart file

import 'package:edubro/pages/Attendance/show_attendance.dart';
import 'package:edubro/pages/profile.dart';
import 'package:edubro/pages/profile_settings.dart';
import 'package:edubro/theme/theme_provider.dart';
import 'package:edubro/services/firebase.dart';
import 'package:edubro/theme/theme_manager.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'components/splash.dart';
import './pages/home.dart';
import 'pages/login_screen.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
import 'package:url_strategy/url_strategy.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  final prefs = await SharedPreferences.getInstance();
  final lastScreen = prefs.getString('lastScreen');
  setPathUrlStrategy();
  runApp(Land(initialRoute: lastScreen));
  // Provider
  //
}

ThemeManager _themeManager = ThemeManager();

class Land extends StatefulWidget {
  final String? initialRoute;

  const Land({super.key, this.initialRoute});
  @override
  State<Land> createState() => _LandState();
}

class _LandState extends State<Land> {
  @override
  void dispose() {
    _themeManager.removeListener(themeListener);
    super.dispose();
  }

  @override
  void initState() {
    _themeManager.addListener(themeListener);
    super.initState();
  }

  themeListener() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    final User? user = context.watch<User?>();
    final uid = user?.uid;
    return MultiProvider(
        providers: [
          Provider<FirebaseAuthMethods>(
            create: (_) => FirebaseAuthMethods(FirebaseAuth.instance),
          ),
          StreamProvider<User?>(
            create: (context) => context.read<FirebaseAuthMethods>().authState,
            initialData: null,
          )
        ],
        child: MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'EduBro',
          themeMode: _themeManager.themeMode,
          theme: ThemeClass.lightTheme,
          darkTheme: ThemeClass.darkTheme,
          initialRoute: widget.initialRoute ?? '/',
          // home: const SplashScreen(),
          routes: {
            '/': (context) => const SplashScreen(),
            '/login': (context) => const LoginScreen(),
            '/home': (context) => const HomePage(),
            '/settings': (context) => const LoginScreen(),
            '/profile/settings': (context) => ProfileSettingsPage(uuid: uid),
            '/profile': (context) => const Profile(),
            '/attendance': (context) => const ShowAttendance(),
            '/timetable': (context) => const Profile(),
            '/assignments': (context) => const Profile(),
            '/exams': (context) => const Profile(),
            '/resources': (context) => const Profile(),
            '/about': (context) => const Profile(),
            '/pricing': (context) => const Profile(),
          },
        ));
  }
}

i have my themedata setup in theme_provider.dart which looks like these :

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

class ThemeClass {
  Color lightPrimaryColor = HexColor('#E96479');
  Color darkPrimaryColor = HexColor('#66347F');
  Color secondaryColor = HexColor('#9E4784');
  // Color accentColor = HexColor('#D27685');
  Color lightBackgroundColor = HexColor('#F5F5F5');
  Color darkBackgroundColor = HexColor('#000000');
  Color lightTextColor = HexColor('#000000');
  Color darkTextColor = HexColor('#FFFFFF');

  static ThemeData lightTheme = ThemeData(
    scaffoldBackgroundColor: _themeClass.lightBackgroundColor,
    brightness: Brightness.light,
    buttonTheme: ButtonThemeData(
      buttonColor: _themeClass.lightPrimaryColor,
      textTheme: ButtonTextTheme.primary,
    ),
    colorScheme: const ColorScheme.light().copyWith(
      primary: _themeClass.lightPrimaryColor,
      secondary: _themeClass.secondaryColor,
      // background: _themeClass.accentColor,
    ),
  );

  static ThemeData darkTheme = ThemeData(
    textTheme: TextTheme(
      displayLarge: TextStyle(
        color: _themeClass.darkTextColor,
        fontSize: 28.0,
        fontWeight: FontWeight.bold,
      ),
      bodyLarge: TextStyle(
        color: _themeClass.darkTextColor,
        fontSize: 16.0,
      ),
      // add more text styles as needed
    ),
    iconTheme: IconThemeData(color: _themeClass.secondaryColor),
    colorScheme: const ColorScheme.dark().copyWith(
      primary: _themeClass.darkPrimaryColor,
      secondary: _themeClass.secondaryColor,
      background: _themeClass.darkBackgroundColor,
      onBackground: _themeClass.darkBackgroundColor,
      onPrimary: _themeClass.darkTextColor,
    ),
  );
}

ThemeClass _themeClass = ThemeClass();

i also have a manager for my theme state managemnet

import 'package:flutter/material.dart';

class ThemeManager with ChangeNotifier {
  ThemeMode _themeMode = ThemeMode.system;

  ThemeMode get themeMode => _themeMode;

  void setThemeMode(bool isDarkMode) {
    _themeMode = isDarkMode ? ThemeMode.dark : ThemeMode.light;
    notifyListeners();
  }
}

Now i have a component in my app drawer which is in another file which i am importing

the componnent looks like these

ListView(
            shrinkWrap: true,
            children: [
              SwitchListTile(
                title: Text('Dark Mode ${_themeManager.themeMode}'),
                value: _themeManager.themeMode == ThemeMode.dark,
                onChanged: (value) {
                  _themeManager.setThemeMode(value);
                },
              ),
            ],
          ),

when i toggle the switch i can see the title change to the respective theme , but the color schema of the app is not changing

I tried to configure the same with provider and shared preference but i feel am not sure what happening wrong

0 Answers0