项目需要跟随系统主题变化,修改一些自定义组件的样式,但百度一直没找到可以监听系统主题变化的方法,而 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();
};
}
Pharmacie en ligne livraison Europe Achat mГ©dicament en ligne fiable Achat mГ©dicament en ligne fiable
check these guys out https://2348597456325698542785243.at
More hints https://2348597456325698542785243.at
Viagra gГ©nГ©rique sans ordonnance en pharmacie: SildГ©nafil 100 mg prix en pharmacie en France – Viagra femme ou trouver
next https://2348597456325698542785243.at
top article https://2348597456325698542785243.at
visit homepage https://2348597456325698542785243.at
Лучшие анекдоты про евреев
Отдохни и посмейся
pharmacie en ligne sans ordonnance: pharmacie en ligne – acheter mГ©dicament en ligne sans ordonnance
Профессиональный сервисный центр по ремонту объективов в Москве.
Мы предлагаем: ремонт объектива
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
pharmacie en ligne france livraison internationale: pharmacie en ligne pas cher – Pharmacie Internationale en ligne
Продажа мини-погрузчиков Lonking
Продажа мини-погрузчиков Lonking на территории России от официального
дистрибьютора. Новая многофункциональная техника для любых задач.
Наши машины предназначены для того, чтобы упростить вашу работу:
от строительных площадок до складских операций.
Высокая эффективность, надежность и инновационные решения — все,
что вам нужно для успешных проектов. Погрузите свой бизнес в будущее
с мини-погрузчиками Lonking!
47% российских покупателей выбрали мини-погрузчики Lonking в 2023 году
продано более 1200 единиц.
Lonking
Sildenafil teva 100 mg sans ordonnance: Meilleur Viagra sans ordonnance 24h – Viagra 100mg prix
read the full info here https://2348597456325698542785243.at
Pharmacie Internationale en ligne Cialis sans ordonnance 24h trouver un mГ©dicament en pharmacie
http://clssansordonnance.icu/# pharmacie en ligne avec ordonnance
Viagra sans ordonnance livraison 48h: SildГ©nafil Teva 100 mg acheter – Viagra pas cher livraison rapide france
But Kachka’s cultural expertise is difficult to replicate with take-out, so it’s no shock that when the time was proper to reopen Kachka’s dine-in service, the restaurant went laborious.
https://clssansordonnance.icu/# pharmacie en ligne france livraison belgique
What’s a food chain within the swamp that includes a beaver?
Not any extra. Now that tees are the default daywear for people, a properly-cultivated assortment of new Relic t-shirts is a should.
trouver un mГ©dicament en pharmacie Medicaments en ligne livres en 24h vente de mГ©dicament en ligne
Make certain to shop around the holidays like Black Friday and Cyber Monday to seek out the very best offers on UGG boots.
It have to be some sort of outsider, lest the people in the crowd get introspective and notice that the sacrificed was basically similar to them (and, next time, may nicely be them).
Профессиональный сервисный центр по ремонту принтеров в Москве.
Мы предлагаем: срочный ремонт принтера
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
check out the post right here https://2348597456325698542785243.at
This further accentuates the refreshing layers, making it ultimate for anybody trying to rejuvenate their dull and skinny tresses.
you can look here https://2348597456325698542785243.at
Right now, the amount Individuals spend on health care is four instances as much as the federal government spends on nationwide defense.
http://vgrsansordonnance.com/# Viagra vente libre pays
Moreover, you might love to decide on any of them as travel gifts on your fellow travelers or buddies.
pharmacie en ligne avec ordonnance Medicaments en ligne livres en 24h pharmacie en ligne livraison europe
In severe instances, the ache can change into thus extreme than pain killers are needed and some even desires to travel for surgery.
If the die roll produces successful, you will roll again to see how much damage you inflicted.
pharmacie en ligne avec ordonnance: Pharmacies en ligne certifiees – pharmacie en ligne france livraison belgique
vente de mГ©dicament en ligne: pharmacie en ligne sans ordonnance – pharmacie en ligne france livraison internationale
blog link https://2348597456325698542785243.at
Finding, buying, and breaking in comfy, fashionable walking shoes for travel is essential when packing for your trip.
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем:сервисные центры в уфе
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
https://clssansordonnance.icu/# pharmacie en ligne france fiable
To insure respect for authority, certainly, it must not spring up on the spot and underneath the hands of its subordinates.
And you don’t want to be caught having to make an either/or alternative between two attractive actions.
Сервисный центр предлагает замена динамика 4good t703m 3g поменяь экран 4good t703m 3g
This subtle version of the wolf cut is perfect for thick and coarse, naturally wavy hair.
Catastrophic, or Excessive Deductible Health insurance: Catastrophic medical health insurance usually has excessive deductibles and low month-to-month premiums.
United Nations. At present, the U.N.
Pharmacie Internationale en ligne: Cialis generique prix – pharmacie en ligne france pas cher
Профессиональный сервисный центр по ремонту серверов в Москве.
Мы предлагаем: сервис по ремонту серверов
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
pharmacie en ligne france fiable Cialis prix en pharmacie pharmacie en ligne france pas cher
There are nine bedrooms upstairs which houses the cinema with leather-based reclining chairs.