项目需要跟随系统主题变化,修改一些自定义组件的样式,但百度一直没找到可以监听系统主题变化的方法,而 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://kvartira-novostroyka2.ru
Помощь в решении задач https://zadachireshaem-online.ru. Опытные авторы с профессиональной подготовкой окажут консультацию в решении задач на заказ недорого, быстро, качественно
Way cool! Some extremely valid points! I appreciate you penning this write-up and also the rest of the website is also really good.
купить квартиру от застройщика цены квартиры от застройщика
рейтинг прогнозистов https://rejting-kapperov12.ru/ .
лучшие капперы в телеграмме лучшие капперы в телеграмме .
купить квартиру квартиры от застройщика
купить 1 комнатную новостройку https://zastroyshikekb.ru
квартиры от застройщика жк https://zastroyshikekb54.ru
оборудование для конференц зала купить оборудование для конференц зала купить .
coindarwin web3 academy
The Untold Account Behind Solana Originator Toly’s Achievement
Subsequent to A Couple of Portions of Coffee and a Beer
Toly, the innovator behind Solana, began his path with a simple routine – two cups of coffee and a beer. Unaware to him, these moments would set the wheels of his future. Nowadays, Solana remains as a formidable participant in the cryptocurrency world, featuring a market value of billions.
Initial Ethereum ETF Sales
The recently launched Ethereum ETF recently was introduced with a huge trading volume. This significant event experienced numerous spot Ethereum ETFs from multiple issuers be listed on American exchanges, introducing extraordinary activity into the typically steady ETF trading space.
SEC Sanctions Ethereum ETF
The U.S. SEC has sanctioned the Ethereum exchange-traded fund for listing. As a crypto asset featuring smart contracts, Ethereum is expected to significantly impact on the cryptocurrency industry due to this approval.
Trump’s Crypto Maneuver
With the election nearing, Trump portrays himself as the ‘Crypto President,’ continually showcasing his endorsement of the digital currency sector to win voters. His tactic contrasts with Biden’s tactic, targeting the attention of the digital currency community.
Elon Musk’s Crypto Moves
Elon Musk, a well-known figure in the digital currency sector and a backer of the Trump camp, created a buzz again, driving a meme coin connected to his actions. His involvement continues to influence market trends.
Binance’s Latest Moves
Binance’s unit, BAM, is now allowed to channel customer funds into U.S. Treasury instruments. Furthermore, Binance observed its seventh year, emphasizing its journey and acquiring numerous regulatory approvals. Simultaneously, Binance also disclosed plans to discontinue several significant crypto trading pairs, affecting different market players.
AI and Market Trends
A top stock analyst from Goldman Sachs recently commented that artificial intelligence won’t trigger a revolution in the economy
оснащение конференц залов оснащение конференц залов .
квартиры от застройщика жк https://novyekvartiry2.ru
квартиры от застройщика жк https://newkvartiry-spb.ru
купить двухкомнатную квартиру в новостройке купить двухкомнатную квартиру в новостройке
купить новую квартиру застройщик https://novye-kvartiryspb.ru
купить новостройку с отделкой https://kvartirukupit43.ru
Everyone loves it whenever people get together and share opinions. Great site, stick with it.
cipro: cipro – cipro ciprofloxacin
amoxicillin discount coupon: amoxicillin where to get – where can i buy amoxicillin without prec
A motivating discussion is worth comment. I do think that you ought to publish more about this subject, it might not be a taboo matter but typically folks don’t talk about these subjects. To the next! Kind regards.
Discover your perfect stay with WorldHotels-in.com, your ultimate destination for finding the best hotels worldwide! Our user-friendly platform offers a vast selection of accommodations to suit every traveler’s needs and budget. Whether you’re planning a luxurious getaway or a budget-friendly adventure, we’ve got you covered with our extensive database of hotels across the globe. Our intuitive search features allow you to filter results based on location, amenities, price range, and guest ratings, ensuring you find the ideal match for your trip. We pride ourselves on providing up-to-date information and competitive prices, often beating other booking sites. Our detailed hotel descriptions, high-quality photos, and authentic guest reviews give you a comprehensive view of each property before you book. Plus, our secure booking system and excellent customer support team ensure a smooth and worry-free experience from start to finish. Don’t waste time jumping between multiple websites – http://www.WorldHotels-in.com brings the world’s best hotels to your fingertips in one convenient place. Start planning your next unforgettable journey today and experience the difference with WorldHotels-in.com!
can you buy doxycycline over the counter usa: doxycycline 50mg – price of doxycycline
Great article! We are linking to this great article on our website. Keep up the great writing.
doxycycline cost: doxycycline gel – doxycycline 1mg
Temp Mail Pretty! This has been a really wonderful post. Many thanks for providing these details.
buy cipro no rx: ciprofloxacin generic price – buy cipro online canada
I couldn’t refrain from commenting. Exceptionally well written!
купить 2 комнатную квартиру в новостройке квартиры от застройщика
https://indibeti.in is a premier online casino offering a wide array of games including slots, table games, and live dealer options. Renowned for its user-friendly interface and robust security measures, Indibet ensures a top-notch gaming experience with exciting bonuses and 24/7 customer support.
купить квартиру в новостройке цены купить квартиру от застройщика цены
купить 1 квартиру в новостройке купить 2 комнатную квартиру в новостройке
I blog often and I seriously appreciate your content. This great article has truly peaked my interest. I will take a note of your website and keep checking for new details about once a week. I opted in for your RSS feed as well.
where to buy cipro online: cipro 500mg best prices – buy cipro without rx
paxlovid pill: buy paxlovid online – paxlovid covid
The future football star Shabab Al-Ahly https://dubai.shabab-al-ahli-ar.com was born in Dubai in 2000. From a young age, he showed exceptional football abilities and joined the youth academy of one of the UAE’s leading clubs, Shabab Al-Ahly.
In the world of football, Atletico Madrid https://spain.atletico-madrid-ar.com has long been considered the second most important club in Spain after the dominant, Real Madrid.
The fascinating story of Ja Morant’s https://spain.atletico-madrid-ar.com meteoric rise, from status from rookie to leader of the Memphis Grizzlies and rising NBA superstar.
Galatasaray https://turkey.galatasaray-ar.com is one of the most famous football clubs in Turkiye, with a glorious and eventful history.
can i purchase cheap clomid no prescription: can you buy clomid prices – get cheap clomid for sale
AC Milan https://italy.milan-ar.com is one of the most successful and decorated football clubs in the world.
Ремонт плоской кровли https://remontiruem-krovly.ru в Москве, цена работы за 1 м?. Прайс лист на работы под ключ, отзывы и фото.
бумажный пакет с логотипом печать наклеек
Thai Company Directory https://thaicorporates.com List of companies and business information.
where can i buy amoxicillin online: over the counter amoxicillin canada – amoxicillin 500mg capsule cost
http://clomiddelivery.pro/# where to buy clomid tablets
where can i buy cheap clomid pill: can i buy generic clomid – where to get cheap clomid without dr prescription
коллекция порно смотреть онлайн http://porn-library.ru .
Real Madrid’s https://spain.real-madrid-ar.com history goes back more than a century. The club was founded in 1902 by a group of football enthusiasts led by Juan Padilla
FC Bayern Munich (Munich) https://germany.bayern-munchen-ar.com is one of the most famous and recognized football clubs in Germany and Europe