Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Easiest way to add support for light and dark theme in your flutter app.

License

NotificationsYou must be signed in to change notification settings

BirjuVachhani/adaptive_theme

Repository files navigation

adaptive_theme

Adaptive Theme

Easiest way to add support forlight anddark theme in your Flutter app. It allows to manually set light or dark theme and also lets you definethemes based on the system. It also persists the theme modes changes across app restarts.

BuildTestsCodecovPub Version

Demo:Adaptive Theme

Index

Getting Started

add following dependency to yourpubspec.yaml

dependencies:adaptive_theme:<latest_version>

Initialization

You need to wrap yourMaterialApp withAdaptiveTheme in order to apply themes.

import'package:adaptive_theme/adaptive_theme.dart';import'package:flutter/material.dart';voidmain() {runApp(MyApp());}classMyAppextendsStatelessWidget {@overrideWidgetbuild(BuildContext context) {returnAdaptiveTheme(      light:ThemeData.light(useMaterial3:true),      dark:ThemeData.dark(useMaterial3:true),      initial:AdaptiveThemeMode.light,      builder: (theme, darkTheme)=>MaterialApp(        title:'Adaptive Theme Demo',        theme: theme,        darkTheme: darkTheme,        home:MyHomePage(),      ),    );  }}

Changing Theme Mode

Now that you have initialized your app as mentioned above. It's very easy and straight forward to change your theme modes:light to dark, dark to light or to system default.

// sets theme mode to darkAdaptiveTheme.of(context).setDark();// sets theme mode to lightAdaptiveTheme.of(context).setLight();// sets theme mode to system defaultAdaptiveTheme.of(context).setSystem();

Toggle Theme Mode

AdaptiveTheme allows you to toggle between light, dark and system theme the easiest way possible.

AdaptiveTheme.of(context).toggleThemeMode();

Changing Themes

If you want to change the theme entirely like change all the colors to some other color swatch, then you can usesetTheme method.

AdaptiveTheme.of(context).setTheme(  light:ThemeData(    useMaterial3:true,    brightness:Brightness.light,    colorSchemeSeed:Colors.purple,  ),  dark:ThemeData(    useMaterial3:true,    brightness:Brightness.dark,    colorSchemeSeed:Colors.purple,  ),);

Reset Theme

AdaptiveTheme is smart enough to keep yourdefault themes handy that you provided at the time of initialization. You can fallback to those default themes in a very easy way.

AdaptiveTheme.of(context).reset();

This will reset yourtheme as well astheme mode to theinitial values provided at the time of initialization.

Set Default Theme

AdaptiveTheme persists theme mode changes across app restarts and uses the default themes to set theme modes(light/dark) on. You can change this behavior if you want to set a different theme as default theme other then the one provided at the time of initialization.

This comes handy when you're fetching themes remotely on app starts and setting theme as current theme.

Doing so is quit easy. You would set a new theme normally as you do by callingsetTheme method but this time, with a flagisDefault set to true.

This is only useful when you might want to reset to default theme at some point.

AdaptiveTheme.of(context).setTheme(  light:ThemeData(    useMaterial3:true,    brightness:Brightness.light,    colorSchemeSeed:Colors.blue,  ),  dark:ThemeData(    useMaterial3:true,    brightness:Brightness.dark,    colorSchemeSeed:Colors.blue,  ),  isDefault:true,);

Get ThemeMode at App Start

When you change your theme, next app run won't be able to pick the most recent theme directly before rendering with default theme first time. This is because at time of initialization, we cannot run async code to get previous theme mode. However it can be avoided if you make yourmain() method async and load previous theme mode asynchronously. Below example shows how it can be done.

voidmain()async {WidgetsFlutterBinding.ensureInitialized();final savedThemeMode=awaitAdaptiveTheme.getThemeMode();runApp(MyApp(savedThemeMode: savedThemeMode));}
AdaptiveTheme(  light: lightTheme,  dark: darkTheme,  initial: savedThemeMode??AdaptiveThemeMode.light,  builder: (theme, darkTheme)=>MaterialApp(    title:'Adaptive Theme Demo',    theme: theme,    darkTheme: darkTheme,    home:MyHomePage(),  ),)

Notice that I passed the retrieved theme mode to my material app so that I can use it while initializing the default theme. This helps avoiding theme change flickering on app startup.

Listen to the theme mode changes

You can listen to the changes in the theme mode via aValueNotifier. This can be useful when designing theme settings screen or developing ui to show theme status.

AdaptiveTheme.of(context).modeChangeNotifier.addListener(() {// do your thing.});

Or you can utilize it to react on UI with

ValueListenableBuilder(  valueListenable:AdaptiveTheme.of(context).modeChangeNotifier,  builder: (_, mode, child) {// update your UIreturnContainer();  },);

Using floating theme button overlay

Starting fromv3.3.0, you can now setdebugShowFloatingThemeButton totrue and enable a floating button that canbe used to toggle theme mode very easily. This is useful when you want to test your app with both light and dark themewithout restarting the app or navigating to settings screen where your theme settings are available.

AdaptiveTheme(  light:ThemeData.light(),  dark:ThemeData.dark(),  debugShowFloatingThemeButton:true,// <------ add this line  initial:AdaptiveThemeMode.light,  builder: (theme, darkTheme)=>MaterialApp(    theme: theme,    darkTheme: darkTheme,    home:MyHomePage(),  ),);
floating_button.mp4

Ceveats

Non-Persist theme changes

This is only useful in scenarios where you load your themes dynamically from network in the splash screen or some initial screens of the app. Please note thatAdaptiveTheme does not persist the themes, it only persists the theme modes(light/dark/system). Any changes made to the provided themes won't be persisted and you will have to do the same changes at the time of the initialization if you want them to apply every time app is opened. e.g changing the accent color.

Using SharedPreferences

This package usesshared_preferences plugin internally to persist theme mode changes. If your app usesshared_preferences which might be the case all the time, clearing yourshared_preferences at the time of logging out or signing out might clear these preferences too. Be careful not to clear these preferences if you want it to be persisted.

/// Do not remove this key from preferencesAdaptiveTheme.prefKey

You can use above key to exclude it while clearing the all the preferences.

Or you can callAdaptiveTheme.persist() method after clearing the preferences to make it persistable again as shown below.

final prefs=awaitSharedPreferences.getInstance();await prefs.clear();AdaptiveTheme.persist();

Using CupertinoTheme

Wrap yourCupertinoApp withCupertinoAdaptiveTheme in order to apply themes.

import'package:adaptive_theme/adaptive_theme.dart';import'package:flutter/material.dart';voidmain() {runApp(MyApp());}classMyAppextendsStatelessWidget {@overrideWidgetbuild(BuildContext context) {returnCupertinoAdaptiveTheme(      light:CupertinoThemeData(        brightness:Brightness.light,      ),      dark:CupertinoThemeData(        brightness:Brightness.dark,      ),      initial:AdaptiveThemeMode.light,      builder: (theme)=>CupertinoApp(        title:'Adaptive Theme Demo',        theme: theme,        darkTheme: darkTheme,        home:MyHomePage(),      ),    );  }}

Changing Cupertino Theme

// sets dark themeCupertinoAdaptiveTheme.of(context).setDark();// sets light themeCupertinoAdaptiveTheme.of(context).setLight();// sets system default themeCupertinoAdaptiveTheme.of(context).setSystem();

Contribution

You are most welcome to contribute to this project!

Please have a look atContributing Guidelines, before contributing and proposing a change.

Liked Adaptive Theme?

Show some love and support by starring the repository.

Or You can

Buy Me A Coffee

License

Copyright © 2020 Birju VachhaniLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at    http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.

[8]ページ先頭

©2009-2025 Movatter.jp