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.
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:
[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.
2
Answers
Solution:
The issue is that
primarySwatch
expects aMaterialColor
, butColors.yellow
is just aColor
. To fix this, you need to create a customMaterialColor
. Here’s how you can do it:Alternatively, if you don’t need a custom color and can use a predefined material swatch, you can do this:
This should resolve the issue and apply the correct color to your app.
Tags: [flutter] [dart] [flutter-layout] [flutter-theme]
Use colorSchemeSeed instead.