'Flutter : dark Mode and save another data to localstorage

I added dark mode to my application with the system below. It works without problems, but I can't put any other values in localstorage. I tried many ways, but in no way could I add any other data next to the dark mode data. I want to keep profile picture data. There is no problem in the incoming data. There is a problem in saving the incoming data.

I guess I can't access it from outside as each method is instantiated separately. But no matter what I tried I couldn't change the system, the app was always crashing.

When I try to create localstorage in a separate place using the Sharedpreferences helper class and put the data in it, it does not put the data directly. Data is coming, but it is not saving in the save method.

I believe there is a simple solution, but I could not solve it. Do you have any suggestions?

Theme Provider

import 'package:hexcolor/hexcolor.dart';
import 'package:pomodoro_app/Providers/shared_preferences_helper.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ThemeProvider with ChangeNotifier {
  SharedPreferences? sharedPreferences;
  ThemeData? _themeData;

  ThemeData? getTheme() => _themeData;

  final darkTheme = ThemeData(
    appBarTheme: AppBarTheme(
      color: HexColor('#323232'),
      elevation: 0,
    ),
    // Progress
    secondaryHeaderColor: Colors.redAccent,
    progressIndicatorTheme:
        const ProgressIndicatorThemeData(color: Colors.white),
    primaryColor: Colors.white,
    // Scafold
    scaffoldBackgroundColor: HexColor('#323232'),
    brightness: Brightness.light,
  );

  final lightTheme = ThemeData(
    appBarTheme: AppBarTheme(
      color: HexColor('#5F5FFF'),
      elevation: 0,
    ),
    progressIndicatorTheme:
        ProgressIndicatorThemeData(color: Colors.grey.shade300),
    // Progress Border
    secondaryHeaderColor: HexColor('#D047FF'),
    brightness: Brightness.light,
    scaffoldBackgroundColor: HexColor('#5F5FFF'),
  );

  // methods for shared preferences
  void initSharedPreferences() async {
    // sharedPreferences = await SharedPreferences.getInstance();
    await SharedPreferencesHelper.init();
    sharedPreferences = SharedPreferencesHelper.instance;
    notifyListeners();
  }

  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");
    }
  }

  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);
  }

  ThemeProvider() {
    readData('themeMode').then((value) {
      // print('Selected Theme Data from Local 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;
    saveData('themeMode', 'dark');
    notifyListeners();
  }

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

Main.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pomodoro_app/Providers/theme_provider.dart';
import 'package:provider/provider.dart';

import 'Extentions/codegen_loader.g.dart';
import 'Screens/homescreen.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // Init Easy Localization
  EasyLocalization.ensureInitialized();
  var _themeMode = await ThemeProvider().readData('themeMode');
  // Portrait Mode Lock
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
  runApp(
    ChangeNotifierProvider(
      create: (_) => ThemeProvider(),
      builder: (context, snapshot) => EasyLocalization(
        path: 'lib/langs',
        supportedLocales: const [
          Locale('en'),
          Locale('tr'),
        ],
        assetLoader: CodegenLoader(),
        fallbackLocale: Locale('en'),
        child: PomodoroApp(
          themeMode: _themeMode,
        ),
      ),
    ),
  );
}

class PomodoroApp extends StatelessWidget {
  PomodoroApp({Key? key, required this.themeMode}) : super(key: key);

  var themeMode;

  @override
  Widget build(BuildContext context) {
    return Consumer<ThemeProvider>(builder: (context, theme, child) {
      return ScreenUtilInit(
        designSize: const Size(375, 812),
        builder: () => MaterialApp(
          builder: (context, widget) {
            ScreenUtil.setContext(context);
            return MediaQuery(
              data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
              child: widget!,
            );
          },
          title: 'Timefaze',
          locale: context.locale,
          supportedLocales: context.supportedLocales,
          localizationsDelegates: context.localizationDelegates,
          debugShowCheckedModeBanner: false,
          theme: theme.getTheme(),
          home: const HomeScreen(),
        ),
      );
    });
  }
}

Shared preferences helper


class SharedPreferencesHelper {
  static SharedPreferences? _instance;
  static SharedPreferences get instance => _instance!;

  static Future<SharedPreferences> init() async {
    _instance ??= await SharedPreferences.getInstance();
    return _instance!;
  }
}


Sources

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

Source: Stack Overflow

Solution Source