乐闻世界logo
搜索文章和话题

How to check if dark mode is enabled on iOS/Android using Flutter?

1个答案

1

In Flutter, checking whether dark mode is enabled on iOS or Android devices is a relatively straightforward process. Flutter provides built-in tools and APIs to help you easily determine the current theme mode. Here are the steps to check if dark mode is enabled on the device:

1. Use MediaQuery to Get Current Theme Brightness

The MediaQuery class in the Flutter framework allows access to media query information, including the device's brightness (light mode or dark mode). You can check the current theme as follows:

dart
import 'package:flutter/material.dart'; class MyWidget extends StatelessWidget { Widget build(BuildContext context) { // Retrieve current theme brightness var brightness = MediaQuery.of(context).platformBrightness; // Determine if dark mode is enabled bool isDarkMode = brightness == Brightness.dark; return Scaffold( body: Center( child: Text(isDarkMode ? "Dark mode is enabled" : "Dark mode is not enabled"), ), ); } }

In this example, MediaQuery.of(context).platformBrightness retrieves the current device's brightness setting. If it returns Brightness.dark, the device is in dark mode.

2. Use Theme in ThemeData to Get Current Theme Brightness

Another approach is to directly use the Theme class to obtain the current theme's brightness:

dart
import 'package:flutter/material.dart'; class MyWidget extends StatelessWidget { Widget build(BuildContext context) { // Get current theme brightness via Theme var brightness = Theme.of(context).brightness; // Determine if dark mode is enabled bool isDarkMode = brightness == Brightness.dark; return Scaffold( body: Center( child: Text(isDarkMode ? "Dark mode is enabled" : "Dark mode is not enabled"), ), ); } }

Here, Theme.of(context).brightness returns the current theme's brightness setting, which functions similarly to MediaQuery but is directly tied to the active theme data.

Summary

By implementing these two methods, you can easily verify if dark mode is enabled on the device within a Flutter application. This is highly valuable for enhancing user experience and interface adaptability, particularly when dynamically adjusting UI elements based on the theme.

2024年8月8日 01:05 回复

你的答案