Home > front end >  Flutter - Switching between dark and light modes
Flutter - Switching between dark and light modes

Time:10-20

import 'package:flutter/material.dart';

ThemeData lightThemeData(BuildContext context) {
  return ThemeData.light().copyWith(
    primaryColor: Colors.teal,
    backgroundColor: Colors.white,
    scaffoldBackgroundColor: Colors.white,
    appBarTheme: const AppBarTheme(
      backgroundColor: Colors.white,
    ),
  );
}

// dark Theme
ThemeData darkThemeData(BuildContext context) {
  return ThemeData.dark().copyWith(
    primaryColor: Colors.tealAccent,
    backgroundColor: Colors.grey[850],
    scaffoldBackgroundColor: Colors.grey[850],
    appBarTheme: AppBarTheme(
      backgroundColor: Colors.grey[850],
    ),
  );
}

I have my light and dark themes defined. I have a bool to switch them which is changing correctly but the theme is not switching.

Switch(
              value: isDark,
              onChanged: (value) {
                setState(() {
                  isDark = value;
                });
              },

I'm guessing the below is the problem? Is there anwyay to get this to work?

 theme: isDark ? darkThemeData(context) : lightThemeData(context),

CodePudding user response:

Usually you'll want to specify both at the same time by providing a light and a dark theme (theme and darkTheme properties in ThemeData respectively).

To then switch between themes, you use the themeMode attribute in ThemeData, this is either set to ThemeMode.light, ThemeMode.dark or ThemeMode.system, with the latter automatically adapting on system theme change. If you want to manually change it, you'll have to use a state management tool of your choice (e.g. provider).

I hope this helps.

CodePudding user response:

I'm not sure if you've coded it the way below but it switches the theme.

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  ThemeData lightThemeData(BuildContext context) {
    return ThemeData.light().copyWith(
      primaryColor: Colors.teal,
      backgroundColor: Colors.white,
      scaffoldBackgroundColor: Colors.white,
      appBarTheme: const AppBarTheme(
        backgroundColor: Colors.white,
      ),
    );
  }

  ThemeData darkThemeData(BuildContext context) {
    return ThemeData.dark().copyWith(
      primaryColor: Colors.tealAccent,
      backgroundColor: Colors.grey[850],
      scaffoldBackgroundColor: Colors.grey[850],
      appBarTheme: AppBarTheme(
        backgroundColor: Colors.grey[850],
      ),
    );
  }

  bool isDark = false;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: isDark ? darkThemeData(context) : lightThemeData(context),
      home: Scaffold(
        appBar: AppBar(
            title: Text(isDark ? "Dark" : "Light",
                style: TextStyle(color: isDark ? Colors.white : Colors.black)),
            actions: [
              Switch(
                value: isDark,
                onChanged: (value) {
                  setState(() {
                    isDark = value;
                  });
                },
              )
            ]),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Center(
                child: Padding(
              padding: const EdgeInsets.all(50),
              child: Text(
                  """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"""),
            ))
          ],
        ),
      ),
    );
  }
}
  • Related