Adding Dark Mode Feature with Flutter

Adding Dark Mode Feature with Flutter

Introduction

Flutter is a UI toolkit used for developing modern and stylish mobile applications. One of the features acclaimed by developers is the Dark Mode support, which enhances user experience. In this article, we will examine step by step how to add Dark Mode to your application with Flutter.

How to Add Dark Mode Support in Flutter?

Step 1: Basic Configuration

To enable Dark Mode support in your Flutter application, you need to configure the theme settings of the MaterialApp component. In the code example below, both light and dark theme settings are shown.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Dark Mode',
      theme: ThemeData(
        brightness: Brightness.light,
        primarySwatch: Colors.blue,
      ),
      darkTheme: ThemeData(
        brightness: Brightness.dark,
        primarySwatch: Colors.red,
      ),
      themeMode: ThemeMode.system, // Use the system preference
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Dark Mode Example')),
      body: Center(child: Text('Hello, World!')),
    );
  }
}

Step 2: Testing Dark Mode

After adding the above code to your application, you can test it in both light and dark modes. Changing the display mode from your device settings should automatically reflect the theme change in your application. This allows users to switch appearances according to their preferences.

Conclusion

Adding the Dark Mode feature with Flutter is quite simple and provides a better experience to users. Changing the theme dynamically, especially during nighttime use, reduces eye strain. You can enrich your application with this feature and increase user satisfaction.