flutterdartflutter-hive

Saving theme in flutter with Hive


so i tried changing theme with provider and heres my main.dart

import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:provider/provider.dart';
import 'package:themetestnew/homepage.dart';
import 'package:themetestnew/theme/theme_provider.dart';


void main() async {
  await Hive.initFlutter();
  await Hive.openBox('myBox');
  runApp(
    ChangeNotifierProvider(
      create: (context) => ThemeProviderNew(),
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: const HomePage(),
      theme: Provider.of<ThemeProviderNew>(context).themeData,
    );
  }
}

and this is my theme provider

import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:themetestnew/theme/theme.dart';

class ThemeProviderNew with ChangeNotifier {
  final _myBox = Hive.box('myBox');
  bool chosenTheme = false;
  ThemeData _themeData = lightMode;

  ThemeData get themeData => _themeData;

  set themeData(ThemeData themeData) {
    _themeData = themeData;
    notifyListeners();
  }

  void toggleTheme() {
    if (themeData == lightMode) {
      themeData = darkMode;
      chosenTheme = false;
    } else {
      themeData = lightMode;
      chosenTheme = true;
    }
    _myBox.put('theme', chosenTheme);
  }
}

how can i save theme and load it at start? i used hive to save a bool but can load theme based on that bool at start i can only change it with a button


Solution

  • with some little changes it worked because hive cant store ThemeData

    ThemeProviderNew() {
        // if the saved theme is null return the default theme otherwise return the saved one.
        chosenTheme = _myBox.get('theme') ?? true;
        if (chosenTheme) {
          _themeData = lightMode;
        } else {
          _themeData = darkMode;
        }
      }