skip to Main Content

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


  1. You can create extension on BuildContext like,

    extension MyThemeExtension on BuildContext {
      ColorScheme get colorSchema => Theme.of(this).colorScheme;
    }
    

    Then use like context.colorSchema; But actually I prefer writing full line of code like

    @override
    Widget build(BuildContext context) {
      final theme = Theme.of(context);
      final colorSchema = theme.colorSchema;
      final textTheme = theme.textTheme;
    
      return Scaffold(...);
    }
    
    Login or Signup to reply.
  2. Create a utility folder and add this code snippet.

    getColorScheme(context) => Theme.of(context).colorScheme;

    Now use it wherever you want as :

    Container(
       'My text',
       color: getColorScheme(context).primary,
      )
    
    Login or Signup to reply.
  3. You can create you own getter for that

    get appColors(BuildContext context)=>Theme.of(context).colorScheme;
    

    And you can call it like

    Container(
       'Example of shorten colorScheme',
       color: appColors(context).onBackground,
      )
    

    Voila !

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search