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 _isDark = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.light(
primary: Colors.blue,
onPrimary: Colors.white,
),
),
darkTheme: ThemeData(
colorScheme: ColorScheme.dark(
primary: Colors.deepPurple,
onPrimary: Colors.white,
),
),
themeMode: _isDark ? ThemeMode.dark : ThemeMode.light,
home: Scaffold(
appBar: AppBar(
title: Text(
'Color Scheme Demo',
style: TextStyle(
color: Theme.of(context).colorScheme.onPrimary,
),
),
backgroundColor: Theme.of(context).colorScheme.primary,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 150,
height: 150,
color: Theme.of(context).colorScheme.primary,
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
setState(() {
_isDark = !_isDark;
});
},
child: const Text('Switch Theme'),
),
],
),
),
),
);
}
}
This app uses ThemeData with ColorScheme.light and ColorScheme.dark to define colors for light and dark modes. The themeMode switches between them based on a boolean state.
The AppBar background uses the theme's primary color, and the title text color uses colorScheme.onPrimary to ensure good contrast.
The colored box in the center uses the primary color from the current theme, so it changes color when switching themes.
The button toggles the theme mode by updating the state, causing the UI to rebuild with the new colors.