Dynamically changing your theme without hassle

Overview

dynamic_theme

Dynamically changing your theme without hassle

This packages manages changing your theme during runtime and persiting that theme.

I wrote a medium post about this, check it out here!

Include in your project

dependencies:
  dynamic_theme: ^1.0.1

run packages get and import it

import 'package:dynamic_theme/dynamic_theme.dart';

if you want the dialog:

import 'package:dynamic_theme/theme_switcher_widgets.dart';

Usage

Wrap your material app like this:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new DynamicTheme(
      defaultBrightness: Brightness.light,
      data: (brightness) => new ThemeData(
        primarySwatch: Colors.indigo,
        brightness: brightness,
      ),
      themedWidgetBuilder: (context, theme) {
        return new MaterialApp(
          title: 'Flutter Demo',
          theme: theme,
          home: new MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    );
  }
}

Change the theme like this:

  void changeBrightness() {
    DynamicTheme.of(context).setBrightness(Theme.of(context).brightness == Brightness.dark? Brightness.light: Brightness.dark);
  }
  
  void changeColor() {
    DynamicTheme.of(context).setThemeData(new ThemeData(
        primaryColor: Theme.of(context).primaryColor == Colors.indigo? Colors.red: Colors.indigo
    ));
  }

When changing the brightness with setBrightness, it is additionally stored in the shared preferences.

Also included

A dialog widget to change the brightness!

Getting Started

For help getting started with Flutter, view our online documentation.

For help on editing package code, view the documentation.

Comments
  • Store setThemeData value in the shared preferences.

    Store setThemeData value in the shared preferences.

    As when changing the brightness with setBrightness, it is additionally stored in the shared preferences.

    So I think it's necessary to do the same for setThemeData

    opened by hupo376787 8
  • Can't get the plugin changes to take effect

    Can't get the plugin changes to take effect

    In main.dart I have this:

    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return new DynamicTheme(
          defaultBrightness: Brightness.light,
          data: (brightness) => new ThemeData(
            primarySwatch: Colors.pink,
            primaryColorBrightness: Brightness.dark,
            accentColor: Colors.lightBlue
          ),
          themedWidgetBuilder: (context, theme) {
            return new MaterialApp(
              title: 'Top Tens',
              theme: theme,
              home: new LandingPage(title: 'TOP TENS'),
            );
          }
        );
    
    
        
      }
    }
    

    and on a screen later on in the app I call this method:

     _setTheme() {
        DynamicTheme.of(context).setBrightness(Brightness.dark);
    }
    

    but nothing happens, and there is no error thrown. Any ideas what I may have done wrong?

    opened by Zaxist 5
  • Deprecated update

    Deprecated update

    Change this at dynamic_theme.dart:

    static DynamicThemeState of(BuildContext context) {
        return context.ancestorStateOfType(const TypeMatcher<DynamicThemeState>());
    }
    

    To this:

    static DynamicThemeState of(BuildContext context) {
        return context.findAncestorStateOfType<State<DynamicTheme>>();
    }
    
    opened by pulstar 4
  • MissingPluginException when loading the theme.

    MissingPluginException when loading the theme.

    The shared-preferences plugin is currently only available for mobile. You could make this library usable for Desktop if you ask if the plugin is accessable before asking for shared preferences.

    [ERROR:c:\b\s\w\ir\cache\builder\src\flutter\lib\ui\ui_dart_state.cc(157)] Unhandled Exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
    #0      DynamicThemeState.loadBrightness (package:dynamic_theme/dynamic_theme.dart:84:37)
    <asynchronous suspension>
    #1      DynamicThemeState.initState (package:dynamic_theme/dynamic_theme.dart:46:5)
    #2      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4640:58)
    #3      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5)
    #4      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
    #5      Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
    #6      RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1142:16)
    #7      RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1113:5)
    #8      RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:1055:17)
    #9      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2607:19)
    #10     RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1054:13)
    #11     WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:935:7)
    #12     WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:917:7)
    #13     _rootRun (dart:async/zone.dart:1129:38)
    #14     _CustomZone.run (dart:async/zone.dart:1026:19)
    #15     _CustomZone.runGuarded (dart:async/zone.dart:928:7)
    #16     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:968:23)
    #17     _rootRun (dart:async/zone.dart:1133:13)
    #18     _CustomZone.run (dart:async/zone.dart:1026:19)
    #19     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:952:23)
    #20     Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:23:15)
    #21     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
    #22     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
    #23     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
    
    opened by jkoenig134 3
  • Please upgrade Shared_preference to newest version

    Please upgrade Shared_preference to newest version

    Hi, First of all thanks so much for a great library. This saves my time quite a lot. please upgrade this library to a newest flutter version, including its dependency especially share_preference.

    Thank you

    opened by NewITCorp 2
  • SDK compatibility error with newest flutter dev channel

    SDK compatibility error with newest flutter dev channel

    After upgrading to the dev channel -- I can't use dynamic_theme due to a SDK compatibility error..??

    Running "flutter packages get" in flutter_login... The current Dart SDK version is 2.1.0-dev.1.0.flutter-ccb16f7282.

    Because flutter_login depends on dynamic_theme from git which requires SDK version <2.0.0, version solving failed. pub get failed (1)

    -- Can this be resolved?

    Cheers!

    opened by sjmcdowall 2
  • Cannot change ThemeData

    Cannot change ThemeData

    My MyApp class

    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return new DynamicTheme(
          defaultBrightness: Brightness.light,
          data: (brightness) => new ThemeData(
            brightness: brightness,
          ),
          themedWidgetBuilder: (context, theme) {
            return new MaterialApp(
              title: 'Omnibus',
              theme: theme,
              home: new SplashScreen(
                title: 'Omnibus',
              ),
            );
          },
        );
      }
    }
    

    How I'm changing the theme:

    new IconButton(
      icon: new Icon(Icons.palette),
      color: Color.fromARGB(255, 15, 84, 108),
      onPressed: (){
        DynamicTheme.of(context).setBrightness(Brightness.dark);    
        DynamicTheme.of(context).setThemeData(new ThemeData(
          primaryColor: Color.fromARGB(255, 15, 84, 108),
          accentColor: Colors.yellow,
        ));
      }
    ),
    

    The brightness is being changed properly, however the primary color or the accent color are not.

    opened by Atulin 2
  • What is correct version #

    What is correct version #

    Can someone please indicate what the latest version number of this library is, the one which supports null-safety? There are a couple posts in the "Issues" which allude to what is supposed to work but nothing definitive (A sampling of a working example from pub spec.yaml is always useful).

    Two weeks ago my project compiled fine. Now I have spent 3 hours trying to resolve issues with this library and the shared_preferences library.

    I have an app that itself is fairly new and has been written to support null safety. And as noted a couple weeks ago all was good. No issues.

    Today I needed to make a small code change and I am now battling version hell on these two libraries for some unknown reason.

    It would be very helpful if someone would document this library's latest version # I can use in the pubspec.yaml file and the version of shared_preferences this library needs for support purposes.

    Thank you.....

    =====

    Note when I place the following in my pubspec.yaml

    dependency_overrides: dynamic_theme: shared_preferences: 2.0.13

    I get the following when I do a "pub get"

    Warning: You are using these overridden dependencies: ! dynamic_theme 1.0.1 ! shared_preferences 2.0.13

    A compile cycle gives me:

    Error: Cannot run with sound null safety, because the following dependencies don't support null safety:

    • package:dynamic_theme
    opened by EHBradford 1
  • Flutter v2 updates

    Flutter v2 updates

    I'm trying to migrate my apps to nullsafety since Flutter 2.0 is in the stable channel now. This package depends on shared_preferences 0.5.x, which prevents me from upgrading to version 2.0.x. The new version has a breaking change; "Setters no longer accept null to mean removing values. If you were previously using set*(key, null) for removing, use remove(key) instead.". Since this package doesn't remove values by passing null to a setter, it should be safe to upgrade. https://pub.dev/packages/shared_preferences/changelog

    It's probably a good idea to make this a major version upgrade, to maintain compatability with projects that doesn't use shared_preferences 2.0.x. This woluld also open the possibility of adding other null-safety related upgrades down the line.

    I also took the libery of fixing some deprecation warnings.

    opened by tverra 1
  • Android embedding v2

    Android embedding v2

    When building the example project, you'll get this massive warning:

    ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    Warning
    ──────────────────────────────────────────────────────────────────────────────
    Your Flutter application is created using an older version of the Android
    embedding. It's being deprecated in favor of Android embedding v2. Follow the
    steps at
    
    https://flutter.dev/go/android-project-migration
    
    to migrate your project.
    ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    

    So I migrated the example project to Android embedding v2 by following the steps in the guide.

    opened by tverra 1
  • The getter 'brightness' was called on null

    The getter 'brightness' was called on null

    I am using this library with switch button. However, I always get this error.

    The getter 'brightness' was called on null. Receiver: null Tried calling: brightness

    How can I solve this? P.S I am new to flutter and I still don't know what this error means. Please help me. Thanks in advanced.

    opened by HeinKhantZaw 1
  • Issue #63

    Issue #63

    Fix #63

    • Changed version number to 2.0.0
    • Migration to null-safety (Fix #62, Fix #60, Fix #59)
    • Now use the ThemeMode instead of Brightness (Fix #49).
    • ThemedWidgetBuilder themedWidgetBuilder takes now the following parameters: BuildContext, ThemeMode, ThemeData.
    • data parameter is now optional and has the type ThemeDataWithThemeModeBuilder.
    • defaultBrightness became defaultThemeMode and use by default ThemeMode.system.
    • loadBrightnessOnStart became loadThemeOnStart.
    • import package:dynamic_theme/dynamic_theme.dart for both DynamicTheme and BrightnessSwitcherDialog.
    opened by TesteurManiak 4
  • dynamic_theme v2.0

    dynamic_theme v2.0

    Hi @Norbert515,

    First of all, thank you for your package, it helped me a lot for the first few Flutter projects I've made.

    Your package seems to be unmaintained for a bit of time so I took the liberty of adapting your original work to make it fit my needs with the most recent releases of Flutter in one of my recent project. I've changed a bit the base behavior you've created to support ThemeMode instead of Brightness changes so the theme data can be updated with the light, dark or system values.

    If you are interested I'd be glad to merge my modifications in your package, but note there is a few breaking changes (this is why I'm talking about a v2.0). You can already check out the code from my repository: https://github.com/TesteurManiak/ygo_collection_manager/blob/main/dynamic_theme/lib/src/dynamic_theme.dart

    And here's a sample of how I'm using it in my project:

    class MyApp extends StatefulWidget {
      const MyApp({Key? key}) : super(key: key);
    
      @override
      State<StatefulWidget> createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      @override
      Widget build(BuildContext context) {
        return DynamicTheme(
          themedWidgetBuilder: (_, themeMode) {
            return MaterialApp(
              themeMode: themeMode,
              darkTheme: MyThemes.dark,
              theme: MyThemes.light,
              initialRoute: LoadingView.routeName,
              onGenerateRoute: generateRoute,
            );
          },
        );
      }
    }
    

    As you can see with the most recent version of Flutter you don't need to change the value of theme depending of the application Brightness anymore, it is the themeMode parameter that will define which of theme or darkTheme should be used.

    So if you are interested I'd be glad to merge my code in your repo so everyone can beneficiate from it (also I could be helping solving the remaining opened issues).

    Here's the issues that would be solved with this new code:

    • #62
    • #60
    • #59
    • #49
    opened by TesteurManiak 1
  • null safety temporary solution

    null safety temporary solution

    you can run your project with --no-sound-null-safety so now you add this line your main.dart file in top(first line) with comment..

    //@dart=2.9 (the 'd' here is lower case)

    opened by adamsyy 0
Owner
Norbert Kozsir
Student, Android Developer, Machine-Learning enthusiast and in love with flutter. Follow me in twitter @ norbertkozsir
Norbert Kozsir
Flutter Radio Player, A Plugin to handle streaming audio without a hassle

Flutter radio plugin handles a single streaming media preciously. This plugin was developed with maximum usage in mind. Flutter Radio player enables S

Sithira Munasinghe 104 Dec 27, 2022
A time tracking app that respects your privacy and the gets the job done without being fancy.

Time Cop A time tracking app that respects your privacy and gets the job done without getting too fancy. Motivation I'd rather not do time-tracking at

Kenton Hamaluik 642 Dec 30, 2022
A tutorial for creating an Ubuntu Linux Flutter app, using the yaru theme

Building a Yaru app with Flutter Summary URL https://github.com/ubuntu/user_manager Category Environment Linux Status Feedback Link Author Frederik Fe

Ubuntu 22 Dec 21, 2022
Flutter Theme Manager with Abstract Factory Design

extheme 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

Veli Bacik 28 Dec 23, 2022
Messaging App Light and Dark Theme

Messaging App Light and Dark Theme

null 1 Sep 26, 2021
A Application for Address Update Theme UIDAI Hackathon 2021

Address_update_Theme_UIDAI_Hackathon Address Update Theme UIDAI Hackathon Application for Address Update Theme UIDAI Hackathon 2021. General This is a

Rahul Ranjan Singh 2 Nov 2, 2021
Pikitia is a social mobile app developed with Flutter, focused around the theme of a Pikit.

Pikitia Pikitia is a social mobile app developed with Flutter, focused around the theme of a Pikit. A Pikit is simply a photo, associated with the loc

Léo Salé 3 Dec 25, 2022
Platform to post/say something without sharing personal information.

Anon is an Open Source Application where it's users will be able to share their thoughts without their identity being revealed i.e Anonymous. When the

Ismael Shakverdiev 18 Sep 13, 2022
An architecture for dynamic UI without client deployment

Server Driven UI Demo Server Driven UI(SDUI)는 서버에서 클라이언트의 UI 컴포넌트를 관리하는 방식. 클라이언트 배포없이 API 응답을 변경하는 것만으로 UI 변경이 가능한 동시에 하위 호환성을 확보할 수 있다. Rust, GraphQ

Simon Park 15 Oct 17, 2022
Send WhatsApp Messages without saving contact

WHATSAPP DIRECT Send WhatsApp Messages without saving contact Installation PlayStore Link: https://play.google.com/store/apps/details?id=com.snapsid.w

Siddharth Chopra 1 Oct 2, 2022
Code generation for immutable classes that has a simple syntax/API without compromising on the features.

Welcome to Freezed, yet another code generator for unions/pattern-matching/copy. 0.14.0 and null-safety Important note: From 0.14.0 and onwards, Freez

Remi Rousselet 1.4k Jan 4, 2023
Whats-link - App to open conversation without having to save the number in WhatsApp

Whats Link App feito para abrir conversa do WhtasApp sem salvar o número do dest

Eduardo Alonso 1 Feb 14, 2022
A Simple Todo app design in Flutter to keep track of your task on daily basis. Its build on BLoC Pattern. You can add a project, labels, and due-date to your task also you can sort your task on the basis of project, label, and dates

WhatTodo Life can feel overwhelming. But it doesn’t have to. A Simple To-do app design in flutter to keep track of your task on daily basis. You can a

Burhanuddin Rashid 1k Jan 6, 2023
A mobile image uploader in which you can upload image to your personal gallery from either your camera or mobile gallery and it can detect your current geographic location and address using firebase firestore and storage.

Image Uploader In Flutter About It is an Image Uploader gallery which tracks your address from which you're uploading using Flutter and Image picker.

Prahen parija 6 Dec 20, 2022
Movie Lib is a mobile application where you can find the movies of your interest. This app provides a collection of movies of different languages according to your interest.

Movie Lib Movie Lib is a mobile application where you can find the movies of your interest. This app provides a collection of movies of different lang

Abhijith Kp 6 Sep 28, 2021
A simple easy to use Flutter DApp , which keeps a track of all your day to day transactions by using Ethereum blockchain in the background which in turn increases your credit score.

Sahayog A simple easy to use Flutter DApp , which keeps a track of all your day to day transactions by using Ethereum blockchain in the background whi

Utkarsh Agarwal 15 May 21, 2022
Your grades across all your devices.

Gradely 2 A Grade Calculator App, that syncs all your Grades across all your devices, built with Flutter and with the amazing backend Appwrite. Screen

Elias Schneider 16 Dec 8, 2022
About This is Personal Expenses Planner. You can add your expenses in to the app and manage your transaction. and you can see How much did you spend on which day. I developed this project using flutter.

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

Darshit Rudani 5 Jul 6, 2022
A web dashboard that allows you to monitor your Chia farm and sends notifications when blocks are found and new plots are completed through a discord bot. It can link multiple farmers/harvesters to your account.

farmr A web dashboard that allows you to monitor your Chia farm and sends notifications when blocks are found and new plots are completed through a di

Gil Nobrega 261 Jan 2, 2023