skip to Main Content

I’m struggling finding a solution to manage the color of my Container’s Borders without hard coding them every time.

I want to define my custom Colors for the Borders in ThemeData for the day mode and the night mode, but I can’t find the right property. At the moment the color chosen by Dart for the borders is dark.

Just to be clear … i wish to write something like this:

 border: Border.all(
   width: width * 0.002,
 ),

without specifying the color.

2

Answers


  1. If you take a look at the Border.all constructor in the source code, it looks like this:

    Border.all({
      Color color = const Color(0xFF000000),
      double width = 1.0,
      BorderStyle style = BorderStyle.solid,
      double strokeAlign = BorderSide.strokeAlignInside,
    })
    

    As you can see, the color parameter defaults to Color(0xFF000000), which is solid black. This means it doesn’t inherit or reference any color from the app’s ThemeData. Unfortunately, this parameter isn’t linked to theme properties that we can easily customize.

    Moreover, extending the Border class to create a custom border that uses something like Theme.of(context).colorScheme.surface for the color isn’t an option, because the Border class doesn’t have access to the context.

    However, if you’re looking for a more flexible way to apply borders consistently throughout your app, you can create a global function. This function can pull color values from the theme and apply them to your borders, like so:

    Border getCustomBorder({
      required BuildContext context,
      double width = 1.0,
    }) {
      return Border.all(
        width: width,
        color: Theme.of(context).colorScheme.surface, // Pull color from the theme
      );
    }
    

    You can then use this function in your widgets like this:

    border: getCustomBorder(
      context: context,
      width: width * 0.002,
    ),
    
    Login or Signup to reply.
  2. You must first create a dart file:

    import 'package:flutter/material.dart';
    
    enum ThemeType { dark, light }
    
    extension AppTheme on ThemeData {
      Color get blue => brightness == Brightness.light ? const Color(0xFF016BE7) : const Color(0xFF012EE9);
    }
    

    you can define each color that you want in dark or light mode

    and you can use this

    Border.all(
        width: width,
        color: Theme.of(context).blue
      )
    

    when you change the theme (light to dark or dark to light)
    colors can be changed automatically.

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