Change Flutter App Theme from Light to Dark

Tiempo de lectura: < 1 minuto

Reading time: < 1 minute

First, we need to add the provider dependency inside the pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  provider: ^5.0.0

To modify the theme of an application, I’ll show an example below:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => ThemeProvider(),
      child: MyApp(),
    ),
  );
}

class ThemeProvider with ChangeNotifier {
  bool _isDarkMode = false;

  ThemeMode get currentTheme => _isDarkMode ? ThemeMode.dark : ThemeMode.light;

  void toggleTheme() {
    _isDarkMode = !_isDarkMode;
    notifyListeners();
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.light(),
      darkTheme: ThemeData.dark(),
      themeMode: Provider.of<ThemeProvider>(context).currentTheme,
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My App'),
      ),
      body: Center(
        child: Consumer<ThemeProvider>(
          builder: (context, themeProvider, _) => ElevatedButton(
            onPressed: () {
              themeProvider.toggleTheme();
            },
            child: Text('Change Theme'),
          ),
        ),
      ),
    );
  }
}

I hope this helps, have a great day!

Leave a Comment