Flutter widget to change `themeMode` during runtime and persist it across restarts.

Overview

theme_mode_handler

version All Contributors

Flutter widget to change themeMode during runtime and persist it across restarts.

Motivation

Flutter 1.9 introduced a new way to control which theme is used: MaterialApp.themeMode. If you have specified the darkTheme and theme properties, you can use themeMode to control it. The property defaults to ThemeMode.system.

This package wraps this functionality and allows you to persist and retrieve the user's preference wherever you want by implementing an interface.

Installation

Add this to your pubspec.yaml:

dependencies:
  theme_mode_handler: ^3.0.0

Usage

  • Create a class that implements the IThemeModeManager interface:
class MyManager implements IThemeModeManager {
  @override
  Future<String> loadThemeMode() async {}

  @override
  Future<bool> saveThemeMode(String value) async {}
}
  • Import the ThemeModeHandler widget, wrap MaterialApp with it and pass it an instance of your manager:
import 'package:theme_mode_handler/theme_mode_handler.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ThemeModeHandler(
      manager: MyManager(),
      builder: (ThemeMode themeMode) {
        return MaterialApp(
          themeMode: themeMode,
          darkTheme: ThemeData(
            brightness: Brightness.dark,
          ),
          theme: ThemeData(
            brightness: Brightness.light,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      },
    );
  }
}
  • Change the themeMode with:
ThemeModeHandler.of(context).saveThemeMode(value);
  • Get the current themeMode with:
ThemeModeHandler.of(context).themeMode;

Check the example folder for a complete example.

API

builder

Type: Widget Function(ThemeMode themeMode).

Function that runs when themeMode changes.

manager

Type: IThemeModeManager.

Implementation of IThemeModeManager to load and save the selected value.

defaultTheme

Type: ThemeMode.

Default value to be used when manager.loadThemeMode returns null or an invalid value.

placeholderWidget

Type: Widget?.

While the themeMode is loaded, you can choose to render a different widget. By default, it'll render an empty container.

Extra

This package exports a dialog and a method to simplify its usage.

  • Import the dialog with:
import 'package:theme_mode_handler/theme_picker_dialog.dart';
  • Use it like this:
void _selectThemeMode(BuildContext context) async {
  final newThemeMode = await showThemePickerDialog(context: context);
  print(newThemeMode);
}

Inspiration

This package is inspired and based on the great package dynamic_theme.

Contributors

Thanks goes to these wonderful people (emoji key):


Arthur Denner

💻 🎨 💡 🚧

This project follows the all-contributors specification. Contributions of any kind welcome!

License

MIT © Arthur Denner

Comments
  • On theme change opens keyboard pad

    On theme change opens keyboard pad

    On theme change opens keyboard pad. This happens only on first change theme invoke. The following changes do not open keyboard pad. The same expirience I noticed using dynamic_theme on which this package based. What is the reason for that?

    question 
    opened by asavchuk 4
  • How to start an app straight in the light theme?

    How to start an app straight in the light theme?

    Let's suppose the darkTheme and theme properties are defined, and since the theme property defaults to ThemeMode.system, then how to start an app straight in the light theme?

    question 
    opened by asavchuk 2
  • WidgetsBindingObserver Listener

    WidgetsBindingObserver Listener

    Hi 👋. Great library!

    This looks to be a near perfect solution for what I'm going for. Have you considered implementing WidgetsBindingObserver to listen for theme mode changes while the app is open?

    The use case I'm thinking of covering is when a user has an app open and has their mode set to system. For example on iOS users can have the mode change at sunset from light to dark. I realize this is a bit of a edge case and maybe not worth the effort.

    If you are interested I'd be happy to PR. Thanks!

    question 
    opened by kmcgill88 2
  • is it supposed to persist to local storage for next use?

    is it supposed to persist to local storage for next use?

    I was wondering if this package is supposed to persist the user's preference of theme on the device. Because I can't figure out of this is my fault or the package is worded so that I think maybe it is supposed to do that when it's not. Thanks

    invalid 
    opened by JosephShepin 0
  • feat: allow management of theme by consumer

    feat: allow management of theme by consumer

    Currently, this library is very restricted - my fault, first Dart/Flutter library 😅

    The current approach forces the usage of shared_preferences but the consumers (devs using the library) must be able to store the preference using whatever approach they prefer like storing locally with Hive or saving it in a database such as Firebase or MongoDB.

    Therefore, we need to change the approach to allow for a manager property which will require an implementation of an interface with methods to load and save the selected themeMode.

    This will require a major version bump.

    enhancement 
    opened by arthurdenner 0
Releases(v3.0.0)
  • v3.0.0(Apr 13, 2021)

    3.0.0

    Features

    BREAKING CHANGES

    • A new placeholderWidget property is supported to display a custom widget while the theme is loaded. It replaces the withFallback property. If not specified, it'll display an empty container as before.
    Source code(tar.gz)
    Source code(zip)
Owner
Arthur Denner
Domain Architect Front-End. From Brazil, living in Sweden. Addicted to TV shows, especially nordic.
Arthur Denner
State Persistence - Persist state across app launches. By default this library store state as a local JSON file called `data.json` in the applications data directory. Maintainer: @slightfoot

State Persistence Persist state across app launches. By default this library store state as a local JSON file called data.json in the applications dat

Flutter Community 70 Sep 28, 2022
It's a universal app template to have a great animated splash screen and liquid slider. Just change the animation if you want (rive) and change the images or colours according to your app.

liquid A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this i

Zikyan Rasheed 28 Oct 7, 2022
A Fluter tabview that text color can change with animation and bg color change with animation

float_tab A Fluter tabview that text color can change with animation and bg color change with animation Getting Started This project is a starting poi

ventureli 1 Dec 8, 2021
ITS A SIMPLE CRYPTO APP THAT GIVES OR DISPLAYS PRICES - %CHANGE AND CHANGE VALUE OF TICKER (VARIOUS CRYPTO ASSERTS)

btcpricetracker A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started

jatin upadhyay 0 Dec 28, 2021
Petrus Nguyễn Thái Học 193 Dec 29, 2022
Widget that gives you the size of the widget in runtime.

Tailor Flutter widget that calculates the size of a widget in runtime. Usage Just wrap your widget with Tailor and get the size in the builder. The bu

Aman Gupta 7 Nov 2, 2022
Widget Runtime for WidgetStudio

flutter_dynamic_widget A Dynamic Widget Runtime from JSON for Flutter Widgets. This package powers https://widget.studio Based on code gen from this p

Rody Davis 61 Dec 6, 2022
Fake Firebase Performance for use during Flutter unit & widget tests.

Fake Firebase Performance Fakes to write unit tests for apps using Firebase Performance monitoring. Instantiate a FakeFirebasePerformance, then pass i

Philipp Bauer 2 Apr 16, 2022
🚰 A BehaviorSubject for Flutter with automatic persist and hydrate

Hydrated Hydrated provides a Subject that automatically persists to Flutter's local storage and hydrates on creation! Easy to consume All values are p

Solid Software 114 Oct 2, 2022
Let's create a complete Flutter User Profile Page with SharedPreferences to persist the user's information in Flutter.

Flutter Tutorial - User Profile & SharedPreferences Let's create a complete Flutter User Profile Page with SharedPreferences to persist the user's inf

Johannes Milke 21 Dec 3, 2022
Persist data with Flutter's Hive NoSQL Database locally on Android, iOS & Web.

Flutter Tutorial - Hive NoSQL Database Persist data with Flutter's Hive NoSQL Database locally on Android, iOS & Web. ✌  Preview App Preview Course Pr

Johannes Milke 54 Dec 31, 2022
Small Flutter app that uses SQLite to persist data.

Crud_With_Flutter_And_Sqlite A new Flutter project. The application allows you to register a user with your name and email, edit and also delete. All

Idelfonso Joás 0 Oct 22, 2022
A web-safe implementation of dart.io.Platforms. Helps avoid the "Unsupported operation: Platform._operatingSystem" runtime error.

Universal Platform - A Web-safe Platform class Currently, if you include the dart.io.Platform anywhere in your code, your app will throw the following

gskinner team 86 Nov 20, 2022
Practice code of simple flutter app to explain how provider works as across the widget state management.

vdo A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this is y

Syed Uzair 9 Nov 7, 2022
This is a simple mobile application which calculates the person expenses during each week and tracks up where he spend his money!

Presonal Expenses Tracker Table of content About the project built with Getting Started installation Running ScreenShots About This is a simple mobile

Abdelaziz Salah 8 Nov 3, 2022
The app that i built during the IITM Session on "Working with APIs in Flutter"

api_test A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this

Aswin Gopinathan 1 Dec 18, 2021
Production-grade project developed during the Reso Coder Academy Flutter Bootcamp: It's a mobile Github repository viewer

RepoStar - GitHub Starred Repository Manager Production-grade project developed during the Reso Coder Academy Flutter Bootcamp. It's a mobile Github s

Kishan Dhankecha 4 Aug 18, 2022
End-to-end mobile app templates that other developers can use during their Flutter development journey.

Flutter UI Templates Welcome Contributors ?? The Robotics Forum always encourages new ideas. Aim ?? Main aim of this repository is to make things fast

The Robotics Forum, VIT Pune 8 Dec 18, 2022
A Flutter app developed during classroom lessons in the Mobile & Gaming 2021/2023 course

quiz A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this is

Marco Porcaro 2 Oct 11, 2022