flutterflutter-theme

How to get primary color from the theme of a flutter app


I have a problem with theming a flutter app. I cannot get the primary color from of the theme. Here is the example code

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: const ColorScheme.light(
          primary: Colors.blue,
          secondary: Colors.amber,
        ),
        useMaterial3: true,
      ),
      darkTheme: ThemeData(
        colorScheme: const ColorScheme.dark(
          primary: Colors.grey,
          secondary: Colors.white,
        ),
        useMaterial3: true,
      ),
      themeMode: ThemeMode.system,
      home: Scaffold(
        body: Center(
          child: SizedBox(
            height: 200,
            width: 200,
            child: Container(
              color: Theme.of(context).colorScheme.primary,
            ),
          ),
        ),
      ),
    );
  }
}

I want the container to have the primary color of the theme which is blue in light mode and grey in dark mode. But It always shows purple color in both light and dark mode

Light Mode

enter image description here

Dark Mode

enter image description here

I have tried different solution many times. But result is same. I am new to flutter. I hope a kind reply. Thank you.


Solution

  • modify to this for most simple

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            colorScheme: const ColorScheme.light(
              primary: Colors.blue,
              secondary: Colors.amber,
              primaryContainer: Colors.blue,
            ),
            useMaterial3: true,
          ),
          darkTheme: ThemeData(
            colorScheme: const ColorScheme.dark(
              primary: Colors.grey,
              secondary: Colors.white,
            ),
            useMaterial3: true,
          ),
          themeMode: ThemeMode.system,
          home: Scaffold(
            body: Builder(builder: (context) {
              return Center(
                child: SizedBox(
                  height: 200,
                  width: 200,
                  child: Container(
                    color: Theme.of(context).colorScheme.primary,
                  ),
                ),
              );
            }),
          ),
        );
      }
    }
    

    the context is not yet aware of the changes in theme