skip to Main Content

I am currently learning flutter and used "primarySwatch" in my to-do app. But it is not working. I don’t know what to do. I have used the color yellow but its showing white.

primarySwatch not working

I tried many things ->

  • Looking for solutions
  • Flutter sdk reinstallation
  • Formatted the laptop but noting happened.

2

Answers


  1. Solution:

    The issue is that primarySwatch expects a MaterialColor, but Colors.yellow is just a Color. To fix this, you need to create a custom MaterialColor. Here’s how you can do it:

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          home: HomePage(),
          theme: ThemeData(
            primarySwatch: createMaterialColor(Color(0xFFFFEB3B)), // Custom yellow color
          ),
        );
      }
    }
    
    MaterialColor createMaterialColor(Color color) {
      List strengths = <double>[.05];
      final swatch = <int, Color>{};
      final int r = color.red, g = color.green, b = color.blue;
    
      for (int i = 1; i < 10; i++) {
        strengths.add(0.1 * i);
      }
      for (var strength in strengths) {
        final double ds = 0.5 - strength;
        swatch[(strength * 1000).round()] = Color.fromRGBO(
          r + ((ds < 0 ? r : (255 - r)) * ds).round(),
          g + ((ds < 0 ? g : (255 - g)) * ds).round(),
          b + ((ds < 0 ? b : (255 - b)) * ds).round(),
          1,
        );
      }
      return MaterialColor(color.value, swatch);
    }
    
    class HomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('To-Do List'),
          ),
          body: Center(
            child: Text('Hello World'),
          ),
        );
      }
    }
    

    Alternatively, if you don’t need a custom color and can use a predefined material swatch, you can do this:

    theme: ThemeData(
      primarySwatch: Colors.amber, // Predefined swatch
    ),
    

    This should resolve the issue and apply the correct color to your app.

    Tags: [flutter] [dart] [flutter-layout] [flutter-theme]

    Login or Signup to reply.
  2. Use colorSchemeSeed instead.

    [colorScheme] is the preferred way to configure colors. The other color properties (as well as primarySwatch) will gradually be phased out, see https://github.com/flutter/flutter/issues/91772.

    MaterialApp(
      theme: ThemeData(colorSchemeSeed: Colors.yellow),
    ...
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search