项目需要跟随系统主题变化,修改一些自定义组件的样式,但百度一直没找到可以监听系统主题变化的方法,而 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();
};
}
https://indiapharmast.com/# top online pharmacy india
You need to be a part of a contest for one of the finest websites on the internet. I will highly recommend this blog!
world pharmacy india online shopping pharmacy india indianpharmacy com
top 10 pharmacies in india: indian pharmacies safe – indian pharmacy
https://indiapharmast.com/# buy prescription drugs from india
best online pharmacy india: pharmacy website india – best online pharmacy india
buying prescription drugs in mexico mexican online pharmacies prescription drugs pharmacies in mexico that ship to usa
mexican drugstore online: mexican rx online – buying prescription drugs in mexico online
canadian pharmacy 24: online canadian pharmacy review – northwest pharmacy canada
http://foruspharma.com/# best online pharmacies in mexico
buying prescription drugs in mexico mexican drugstore online mexican border pharmacies shipping to usa
prescription drugs canada buy online cross border pharmacy canada canada pharmacy world
indian pharmacy paypal: top online pharmacy india – п»їlegitimate online pharmacies india
online pharmacy india: online pharmacy india – top 10 pharmacies in india
Greetings! Very helpful advice in this particular article! It’s the little changes that will make the biggest changes. Thanks a lot for sharing!
Kylie Jenner https://kylie-cosmetics.kylie-jenner-ar.com is an American model, media personality, and businesswoman, born on August 10, 1997 in Los Angeles, California.
Продажа новых автомобилей Hongqi
https://hongqi-krasnoyarsk.ru/buyers/trade-in-form в Красноярске у официального дилера Хончи. Весь модельный ряд, все комплектации, выгодные цены, кредит, лизинг, трейд-ин
Upcoming fantasy MOBA https://bladesofthevoid.com evolved by Web3. Gacha perks, AI and crafting in one swirling solution!
May I simply just say what a relief to uncover an individual who really knows what they are talking about online. You certainly realize how to bring an issue to light and make it important. More and more people have to read this and understand this side of the story. I was surprised that you are not more popular given that you surely possess the gift.
Казахский национальный технический университет https://satbayev.university им. К.Сатпаева
lcd видеостена москва http://www.videosteny-pod-kljuch.ru .
видеостена москва видеостена москва .
That is a very good tip particularly to those new to the blogosphere. Simple but very precise information… Thank you for sharing this one. A must read article!
Football in Saudi Arabia https://al-hilal.saud-abdulhamid-ar.com is gaining more and more popularity and recognition on the international stage, and Saud Abdul Hamid, the young and talented defender of Al Hilal, is a shining example of this success.
Khvicha Kvaratskhelia https://napoli.khvicha-kvaratskhelia-ar.com is a name that in recent years has become a symbol of Georgian football talent and ambition.
Angel Di Maria https://benfica.angel-di-maria-ar.com is a name that will forever remain in the memories of Benfica fans.
Roberto Firmino https://al-ahli.roberto-firmino-ar.com one of the most talented and famous Brazilian footballers of our time, has paved his way to success in different leagues and teams.
Maria Sharapova https://tennis.maria-sharapova-ar.com was born on April 19, 1987 in Nyagan, Russia. When Masha was 7 years old, her family moved to Florida, where she started playing tennis.
bookmarked!!, I love your site!
Muhammad Al Owais https://al-hilal.mohammed-alowais-ar.com is one of the most prominent names in modern Saudi football. His path to success in Al Hilal team became an example for many young athletes.
Kevin De Bruyne https://manchester-city.kevin-de-bruyne-ar.com is a name every football fan knows today.
I could not refrain from commenting. Well written!
Luis Diaz https://liverpool.luis-diaz-ar.com is a young Colombian striker who has enjoyed rapid growth since joining the ” Liverpool” in January 2022.
Can I simply say what a comfort to discover somebody who actually knows what they’re talking about on the net. You definitely know how to bring an issue to light and make it important. More people should read this and understand this side of your story. I was surprised you are not more popular since you surely have the gift.
In 2018, the basketball world witnessed one of the most remarkable transformations in NBA history. LeBron James https://los-angeles-lakers.lebronjames-ar.com one of the greatest players of our time, decided to leave his hometown Cleveland Cavaliers and join the Los Angeles Lakers.
Cristiano Ronaldo https://al-nassr.cristiano-ronaldo.ae is one of the greatest names in football history, with his achievements inspiring millions of fans around the world.
Karim Benzema https://al-ittihad.karimbenzema.ae is a name worthy of admiration and respect in the world of football.
RDBox.de https://rdbox.de bietet schallgedammte Gehause fur 3D-Drucker, die eine sehr leise Druckumgebung schaffen – nicht lauter als ein Kuhlschrank. Unsere Losungen sorgen fur stabile Drucktemperatur, Vibrationsisolierung, Luftreinigung und mobile App-Steuerung.
Hello there! This post could not be written much better! Looking at this article reminds me of my previous roommate! He continually kept preaching about this. I am going to forward this post to him. Fairly certain he will have a great read. I appreciate you for sharing!
When I originally left a comment I seem to have clicked on the -Notify me when new comments are added- checkbox and from now on whenever a comment is added I receive four emails with the exact same comment. Perhaps there is a way you are able to remove me from that service? Kudos.
Good article! We will be linking to this great post on our site. Keep up the great writing.
Hello there, I believe your web site could possibly be having browser compatibility issues. Whenever I look at your site in Safari, it looks fine but when opening in IE, it’s got some overlapping issues. I just wanted to provide you with a quick heads up! Apart from that, excellent website.
Kobe Bryant https://los-angeles-lakers.kobebryant-ar.com also known as the “Black Mamba”, is one of the most iconic and iconic figures in NBA history.
N’Golo Kante https://al-ittihad.ngolokante-ar.com the French midfielder whose career has embodied perseverance, hard work and skill, has continued his path to success at Al-Ittihad Football Club, based in Saudi Arabia.
Сайт https://ps-likers.ru предлагает уроки по фотошоп для начинающих. На страницах сайта можно найти пошаговые руководства по анимации, созданию графики для сайтов, дизайну, работе с текстом и фотографиями, а также различные эффекты.
visit my website https://currencyconvert.net
Айтек https://multimedijnyj-integrator.ru/ .
i-tec.ru https://multimedijnyj-integrator.ru/ .
Football in Saudi Arabia https://al-hilal.ali-al-bulaihi-ar.com has long been one of the main sports, attracting millions of fans. In recent years, one of the brightest stars in Saudi football has been Ali Al-Bulaihi, defender of Al-Hilal Football Club.
Luka Modric https://real-madrid.lukamodric-ar.com can certainly be called one of the outstanding midfielders in modern football.