[flutter]监听系统主题改变

/ 13,848评论 / 56820阅读 / 0点赞

项目需要跟随系统主题变化,修改一些自定义组件的样式,但百度一直没找到可以监听系统主题变化的方法,而 MaterialApp 是有一个设置ThemeMode.system,使得app可以跟随系统主题变化而切换使用传入的theme和darkTheme,因此我就去看了看里面的源码,找到了监听系统主题变化的函数绑定方法。

解决

import 'dart:ui' as ui;
    ui.PlatformDispatcher.instance.onPlatformBrightnessChanged = () {
      // 设置跟随系统主题变化
      followingSystem();
    };
ui.PlatformDispatcher.instance.onPlatformBrightnessChanged = null;
if(null == ui.PlatformDispatcher.instance.onPlatformBrightnessChanged) {
    // 当前没有在监听
} else {
    // 有在监听
}
    ui.PlatformDispatcher.instance.onPlatformBrightnessChanged = () {
       fun1();
       fun2();
       fun3();
       fun4();
       ......
    };
if(ui.PlatformDispatcher.instance.platformBrightness == Brightness.dark) {
    // 系统已经转变为夜间模式
    // app跟随修改主题为夜间
} else {
    // 系统已经转变为白天模式
    // app跟随修改主题为白天
}
// 进入app时手动调用一次 followingSystem(), 然后调用 setFollowingSystem() 绑定监听函数

  void followingSystem() {
    if (ui.PlatformDispatcher.instance.platformBrightness == Brightness.dark) {
      // app跟随修改主题为夜间
    } else {
      // app跟随修改主题为白天
    }
  }

  // 设置跟随系统主题变化
  void setFollowingSystem() {
    ui.PlatformDispatcher.instance.onPlatformBrightnessChanged = () {
      followingSystem();
    };
  }
  1. CharlesCah说道:

    Pharmacie en ligne livraison Europe Achat mГ©dicament en ligne fiable Achat mГ©dicament en ligne fiable

  2. HeathGlact说道:

    Viagra gГ©nГ©rique sans ordonnance en pharmacie: SildГ©nafil 100 mg prix en pharmacie en France – Viagra femme ou trouver

  3. GartandTesee说道:

    Лучшие анекдоты про евреев
    Отдохни и посмейся

  4. HeathGlact说道:

    pharmacie en ligne sans ordonnance: pharmacie en ligne – acheter mГ©dicament en ligne sans ordonnance

  5. Профессиональный сервисный центр по ремонту объективов в Москве.
    Мы предлагаем: ремонт объектива
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  6. HeathGlact说道:

    pharmacie en ligne france livraison internationale: pharmacie en ligne pas cher – Pharmacie Internationale en ligne

  7. CharlesLiabY说道:


    Продажа мини-погрузчиков Lonking

    Продажа мини-погрузчиков Lonking на территории России от официального
    дистрибьютора. Новая многофункциональная техника для любых задач.
    Наши машины предназначены для того, чтобы упростить вашу работу:
    от строительных площадок до складских операций.

    Высокая эффективность, надежность и инновационные решения — все,
    что вам нужно для успешных проектов. Погрузите свой бизнес в будущее
    с мини-погрузчиками Lonking!

    47% российских покупателей выбрали мини-погрузчики Lonking в 2023 году
    продано более 1200 единиц.
    Lonking

  8. HeathGlact说道:

    Sildenafil teva 100 mg sans ordonnance: Meilleur Viagra sans ordonnance 24h – Viagra 100mg prix

  9. CharlesCah说道:

    Pharmacie Internationale en ligne Cialis sans ordonnance 24h trouver un mГ©dicament en pharmacie

  10. Stephenmig说道:

    http://clssansordonnance.icu/# pharmacie en ligne avec ordonnance

  11. HeathGlact说道:

    Viagra sans ordonnance livraison 48h: SildГ©nafil Teva 100 mg acheter – Viagra pas cher livraison rapide france

  12. 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.

  13. Stephenmig说道:

    https://clssansordonnance.icu/# pharmacie en ligne france livraison belgique

  14. What’s a food chain within the swamp that includes a beaver?

  15. Not any extra. Now that tees are the default daywear for people, a properly-cultivated assortment of new Relic t-shirts is a should.

  16. CharlesCah说道:

    trouver un mГ©dicament en pharmacie Medicaments en ligne livres en 24h vente de mГ©dicament en ligne

  17. Make certain to shop around the holidays like Black Friday and Cyber Monday to seek out the very best offers on UGG boots.

  18. 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).

  19. Профессиональный сервисный центр по ремонту принтеров в Москве.
    Мы предлагаем: срочный ремонт принтера
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  20. This further accentuates the refreshing layers, making it ultimate for anybody trying to rejuvenate their dull and skinny tresses.

  21. Right now, the amount Individuals spend on health care is four instances as much as the federal government spends on nationwide defense.

  22. Stephenmig说道:

    http://vgrsansordonnance.com/# Viagra vente libre pays

  23. Moreover, you might love to decide on any of them as travel gifts on your fellow travelers or buddies.

  24. CharlesCah说道:

    pharmacie en ligne avec ordonnance Medicaments en ligne livres en 24h pharmacie en ligne livraison europe

  25. In severe instances, the ache can change into thus extreme than pain killers are needed and some even desires to travel for surgery.

  26. If the die roll produces successful, you will roll again to see how much damage you inflicted.

  27. HeathGlact说道:

    pharmacie en ligne avec ordonnance: Pharmacies en ligne certifiees – pharmacie en ligne france livraison belgique

  28. HeathGlact说道:

    vente de mГ©dicament en ligne: pharmacie en ligne sans ordonnance – pharmacie en ligne france livraison internationale

  29. 委員会オフ说道:

    Finding, buying, and breaking in comfy, fashionable walking shoes for travel is essential when packing for your trip.

  30. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:сервисные центры в уфе
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  31. Stephenmig说道:

    https://clssansordonnance.icu/# pharmacie en ligne france fiable

  32. To insure respect for authority, certainly, it must not spring up on the spot and underneath the hands of its subordinates.

  33. And you don’t want to be caught having to make an either/or alternative between two attractive actions.

  34. Сервисный центр предлагает замена динамика 4good t703m 3g поменяь экран 4good t703m 3g

  35. This subtle version of the wolf cut is perfect for thick and coarse, naturally wavy hair.

  36. Catastrophic, or Excessive Deductible Health insurance: Catastrophic medical health insurance usually has excessive deductibles and low month-to-month premiums.

  37. United Nations. At present, the U.N.

  38. HeathGlact说道:

    Pharmacie Internationale en ligne: Cialis generique prix – pharmacie en ligne france pas cher

  39. Профессиональный сервисный центр по ремонту серверов в Москве.
    Мы предлагаем: сервис по ремонту серверов
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  40. CharlesCah说道:

    pharmacie en ligne france fiable Cialis prix en pharmacie pharmacie en ligne france pas cher

  41. There are nine bedrooms upstairs which houses the cinema with leather-based reclining chairs.

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注