flutter

How to prevent the clipped content inside a container with borderRadius to not overlap the border on each corner


I made a container that supposed to show a picture with a colored border around it, with the addition borderRadius I set it to 8, but then I notice when I set the container to clip the content, it makes the border corner fade like the following:

Content overlap border corner

Here's how I wrote it

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: Container(
            height: 300,
            width: 300,
            decoration: BoxDecoration(
              border: Border.all(color: Colors.red, width: 2),
              borderRadius: const BorderRadius.all(Radius.circular(16)),
            ),
            clipBehavior: Clip.antiAlias,
            child: Container(
              constraints: BoxConstraints.expand(),
              color: Colors.blue,
            ),
          ),
        ),
      ),
    );
  }
}

I want the content not to overlap the border I have, how to do that?


Solution

  • I want the content not to overlap the border I have, how to do that?

    To achieve this, you'll need to set the foregroundDecoration and decoration properties of the Container, the difference between the two is that,foregroundDecoration will paint the decoration in front of the child and decoration will paint behind the child, that is why you get the clipping when just using decoration

    Note: Setting foregroundDecoration with a clipBehavior will trigger an AssertionError as clipBehavior must be specfied with a decoration

    Updating your code to the following, to get the desired effect:

    Center(
      child: Container(
        height: 300,
        width: 300,
        foregroundDecoration: BoxDecoration(
          border: Border.all(color: Colors.red, width: 2),
          borderRadius: const BorderRadius.all(Radius.circular(16)),
        ),
        decoration: BoxDecoration(
          borderRadius: const BorderRadius.all(Radius.circular(16)),
        ),
        clipBehavior: Clip.antiAlias,
        child: Container(
          constraints: BoxConstraints.expand(),
          color: Colors.blue,
        ),
      ),
    ),
    
    

    Preview of foregroundDecoration on a container