项目需要跟随系统主题变化,修改一些自定义组件的样式,但百度一直没找到可以监听系统主题变化的方法,而 MaterialApp 是有一个设置ThemeMode.system,使得app可以跟随系统主题变化而切换使用传入的theme和darkTheme,因此我就去看了看里面的源码,找到了监听系统主题变化的函数绑定方法。
解决
- 首先需要import标准库,flutter自带的,不需要pub等方式下载:
import 'dart:ui' as ui;
- 系统主题变化函数绑定:
- 直接把下面代码中的onPlatformBrightnessChanged 赋值一个我们想执行的函数即可
ui.PlatformDispatcher.instance.onPlatformBrightnessChanged = () {
// 设置跟随系统主题变化
followingSystem();
};
- -
- 如果想取消监听,则同样把它赋值为null
ui.PlatformDispatcher.instance.onPlatformBrightnessChanged = null;
- -
- 如果想判断现在是否有在监听,则判断它是否不为null
if(null == ui.PlatformDispatcher.instance.onPlatformBrightnessChanged) {
// 当前没有在监听
} else {
// 有在监听
}
- -
- 注意 onPlatformBrightnessChanged 其实就是一个变量而已,你如果给它赋值好几次,那显然它的值就是最后一次赋值的结果
- 因此重复赋值并不会让它能执行多个函数
- 如果需要执行多个函数,应当把这些函数放进一个函数里,然后把它赋值给 onPlatformBrightnessChanged :
ui.PlatformDispatcher.instance.onPlatformBrightnessChanged = () {
fun1();
fun2();
fun3();
fun4();
......
};
- 系统主题变化时会执行 onPlatformBrightnessChanged 绑定的函数,那么我怎么知道现在系统的主题是什么类型呢?
- 可以使用如下代码判断:
if(ui.PlatformDispatcher.instance.platformBrightness == Brightness.dark) {
// 系统已经转变为夜间模式
// app跟随修改主题为夜间
} else {
// 系统已经转变为白天模式
// app跟随修改主题为白天
}
- 还有一个问题需要注意,启动app时,并不会触发上面绑定的函数
- 假设我们给app的默认主题是白天模式,此时系统已经是夜间模式,然后用户启动app,此时并不会触发 onPlatformBrightnessChanged ,因此app呈现的还是白天模式
- 解决方法:显然就是进入app时,我们手动执行一次判断系统主题,跟随变化,然后绑定监听函数即可:
// 进入app时手动调用一次 followingSystem(), 然后调用 setFollowingSystem() 绑定监听函数
void followingSystem() {
if (ui.PlatformDispatcher.instance.platformBrightness == Brightness.dark) {
// app跟随修改主题为夜间
} else {
// app跟随修改主题为白天
}
}
// 设置跟随系统主题变化
void setFollowingSystem() {
ui.PlatformDispatcher.instance.onPlatformBrightnessChanged = () {
followingSystem();
};
}
pharmacies in mexico that ship to usa: buying prescription drugs in mexico – mexican mail order pharmacies
mexican mail order pharmacies mexican pharmaceuticals online buying from online mexican pharmacy
http://mexicandeliverypharma.com/# mexican online pharmacies prescription drugs
mexican pharmaceuticals online mexican rx online purple pharmacy mexico price list
buying from online mexican pharmacy: buying from online mexican pharmacy – reputable mexican pharmacies online
mexican online pharmacies prescription drugs: mexican border pharmacies shipping to usa – medicine in mexico pharmacies
Свежие новости https://diesel.kyiv.ua автомобильного рынка, новинки автопрома
The fascinating story of Ja Morant’s https://grizzlies-de-memphis.ja-morant-fr.com meteoric rise, from status from rookie to leader of the Memphis Grizzlies and rising NBA superstar.
mexican drugstore online п»їbest mexican online pharmacies mexican rx online
Авто статті https://road.kyiv.ua з порадами з ремонту та обслуговування. Авто блог з професійними порадами.
Автомобільні новини https://sedan.kyiv.ua України та світу, тест-драйви автомобілів, автоспорт
http://mexicandeliverypharma.com/# mexico drug stores pharmacies
Temp Mail This was beautiful Admin. Thank you for your reflections.
Где найти актуальные промокоды? Узнайте здесь. Где найти актуальные промокоды? Узнайте здесь. .
Рабочие промокоды для всех типов покупок. http://www.free-promocode.ru .
Уникальные предложения по промокодам для вас http://www.promokodbar.ru .
Получите лучшие промокоды прямо сейчас Получите лучшие промокоды прямо сейчас .
PrestigeAvto https://prestige-avto.com.ua України автомобільний журнал
Найбільший автомобільний портал https://mirauto.kyiv.ua України
Щоденні новини https://k-moto.com.ua із автомобільного середовища. Поради автоаматорам. Тест-драйви автомобілів з пробігом та огляди новинок
Undress AI & Bulk Nude AI Generator nudify online. Make AI nudes and bulk generate undress AI photos of any girl for almost free!
DMV Test на русском языке https://papadmv.com тесты с ответами ПДД США 2024. Тренировочные dmv test на русском для сдачи на права, изучите правила дорожного движения США для разных штатов.
Hi, I do think this is an excellent site. I stumbledupon it 😉 I will come back once again since I book-marked it. Money and freedom is the best way to change, may you be rich and continue to guide other people.
Авто статті https://black-star.com.ua з порадами з ремонту та обслуговування
Автомобільні новини https://avtonews.kyiv.ua України. Все для автовласника.
Автоновини України https://avtomobilist.kyiv.ua огляди машин та новини для автомобілістів
Автомобільні новини https://autonovosti.kyiv.ua України та світу, тест-драйви нових авто, поради експертів
Авто статті https://bestauto.kyiv.ua з порадами з ремонту та обслуговування, авто блог з професійними порадами, огляди новинок
Слимофор https://slymofor.ru инновационное средство для быстрого похудения.
Авто статті https://automobile.kyiv.ua з порадами з ремонту та обслуговування, авто блог з професійними порадами, огляди новинок
Щоденні новини https://autoinfo.kyiv.ua із автомобільного середовища. Поради автоаматорам. Тест-драйви
Сериал “911: Служба спасения” рассказывает о работе сотрудников экстренных служб Лос-Анджелеса, включая пожарных, медиков и операторов 911. Они ежедневно сталкиваются с опасными ситуациями, спасая жизни и решая сложные личные проблемы. Смотрите онлайн в хорошем качестве HD, бесплатно, все сезоны.
В нашем интернет магазине https://shop-uggs.ru представлен широкий ассортимент оригинальных женских, мужских и детских UGG Australia. Вы можете купить угги у нас в Москве, а так же с доставкой по России без предоплаты. Мы привозим 2 пары обуви на примерку, вы сможете сначала примерить уги и только потом оплачивать те угги которые вам подошли.
Официальный сайт по продаже оригинальных кроссовок изи буст https://yeezy-boost-shop.ru в Москве. Мы продаем yeezy boost оригинал с доставкой по всей России. В нашей линейке есть такие модели Adidas yeezy 350, yeezy 500, yeezy slide.
самое классное порево http://www.klassny-sex.ru .
классное порево онлайн классное порево онлайн .
coindarwin web3 academy
The Unseen Narrative About Solana’s Originator Toly Yakovenko’s Accomplishment
Subsequent to A Pair of Portions of Java with a Brew
Toly, the visionary behind Solana, commenced his path with a routine routine – coffee and beer. Little did he know, these moments would spark the machinery of his destiny. Nowadays, Solana exists as an influential contender in the blockchain sphere, boasting a billion-dollar market value.
Initial Ethereum ETF Sales
The recently launched Ethereum ETF recently started with a huge trading volume. This historic event observed multiple spot Ethereum ETFs from different issuers commence trading on American exchanges, creating significant activity into the generally calm ETF trading market.
SEC Approved Ethereum ETF
The Securities and Exchange Commission has formally approved the Ethereum exchange-traded fund for being listed. As a digital asset with smart contracts, Ethereum is anticipated to deeply influence the digital currency industry thanks to this approval.
Trump’s Crypto Maneuver
As the election approaches, Trump positions himself as the “President of Crypto,” repeatedly showing his backing of the blockchain space to attract voters. His approach is different from Biden’s tactic, intending to capture the focus of the crypto community.
Elon Musk’s Crypto Moves
Elon, a well-known figure in the blockchain world and a proponent of the Trump camp, shook things up again, promoting a meme coin related to his antics. His participation continues to shape market dynamics.
Binance Updates
The subsidiary of Binance, BAM, has been allowed to invest customer funds into U.S. Treasury instruments. In addition, Binance celebrated its 7th year, highlighting its development and acquiring numerous regulatory approvals. At the same time, the company also made plans to remove several significant crypto trading pairs, impacting various market participants.
Artificial Intelligence and Economic Outlook
A top stock analyst from Goldman Sachs recently observed that artificial intelligence won’t lead to an economic revolution
cheap car rental in Montenegro Montenegro car rental
Автомобільний портал https://allauto.kyiv.ua який захоплює своїми тест-драйвами та новими новинами автосвіту
Новини автомобільного ринку https://autoguide.kyiv.ua та автопромисловості
Автомобільний портал https://autodream.com.ua новини та огляди новинок авторинку.
Мазь для суставов https://sustalits.ru заказать онлайн.
Everyone loves it when folks come together and share thoughts. Great site, continue the good work.
It’s actually a cool and helpful piece of information. I am satisfied that you shared this helpful information with us. Please stay us up to date like this. Thanks for sharing.
When I originally left a comment I seem to have clicked the -Notify me when new comments are added- checkbox and now whenever a comment is added I get 4 emails with the same comment. There has to be an easy method you can remove me from that service? Kudos.
rent a car in Podgorica https://www.montenegro-car-rental-hire.com
Строительство заборов из металлического штакетника под ключ в Санкт-Петербурге https://trudolubov.com/product/zabory-pod-klyuch/zabor-metallicheskiy-shtaketnik/. Цены на сайте.
Газоблоки https://gasoblok.ru являются самым популярным материалом для строительства домов из газобетона, они стали эффективной, надежной и недорогой технологией. Качественные газобетонные блоки производятся промышленным способом и обрабатываются в специальных автоклавах.
Mixing Reinvented ChipMixer For Your Privacy
This blog was… how do I say it? Relevant!! Finally I have found something which helped me. Thank you.