Everytime I need to access the colors of my current Theme in Flutter, I have to write Theme.of(context).colorScheme.{come color}
.
This means I have to write this in almost every line I need to use a color and is a HUGE hassle.
It would perhaps be shorter if I made a variable in every class’ I needed the colors build()
method, like: final colorScheme = Theme.of(context).colorScheme
.
But that still means I have to write this in every class.
Is there a way to make an abbreviation of this that I can import from a file and use in the whole file in all classes without writing the same thing over and over again?
ANSWER:
I found this GitHub repo with the perfect solution for everyone, that was also stated by @Md. Yeasin Sheikh’s answer.
The GitHub repo file with the solution and more convenient shortcuts for most used lines of code:
import 'package:flutter/material.dart';
extension BuildContextExtensions on BuildContext {
ThemeData get _theme => Theme.of(this);
TextTheme get textTheme => _theme.textTheme;
ColorScheme get colorScheme => _theme.colorScheme;
Size get deviceSize => MediaQuery.sizeOf(this);
}
Then, to access the current color scheme: Import the file with this defined extension, and where you want to access the theme, use: context.colorScheme
.
Usage example:
@override
Widget build(BuildContext context) {
return Container(
color: context.colorScheme.primaryContainer,
child: Text(
'Example container',
style: TextStyle(
color: context.colorScheme.onPrimaryContainer
)
)
);
}
3
Answers
You can create extension on
BuildContext
like,Then use like
context.colorSchema;
But actually I prefer writing full line of code likeCreate a utility folder and add this code snippet.
getColorScheme(context) => Theme.of(context).colorScheme;
Now use it wherever you want as :
You can create you own getter for that
And you can call it like
Voila !