import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _isDarkMode = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Dark Mode Demo',
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: _isDarkMode ? ThemeMode.dark : ThemeMode.light,
home: Scaffold(
appBar: AppBar(
title: const Text('Dark Mode Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
_isDarkMode ? 'Dark Mode' : 'Light Mode',
style: const TextStyle(fontSize: 24),
),
const SizedBox(height: 20),
Switch(
value: _isDarkMode,
onChanged: (bool value) {
setState(() {
_isDarkMode = value;
});
},
activeColor: Theme.of(context).colorScheme.secondary,
inactiveThumbColor: Colors.grey,
inactiveTrackColor: Colors.grey.shade400,
semanticLabel: 'Toggle dark mode',
),
],
),
),
),
);
}
}
This app uses a StatefulWidget to keep track of whether dark mode is on or off with the _isDarkMode boolean.
The MaterialApp has theme for light mode and darkTheme for dark mode. The themeMode property switches between them based on _isDarkMode.
Inside the screen, a Switch widget lets the user toggle dark mode. When toggled, it calls setState to update _isDarkMode, which rebuilds the app with the new theme.
The text above the switch updates to show "Light Mode" or "Dark Mode" so the user knows the current mode.
This approach follows Flutter's recommended way to support dark mode with easy switching.