flutterdartthemes

Managing Container's Borders color using ThemeData


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.


Solution

  • 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,
    ),