如何防止具有 borderRadius 的容器内的剪切内容不与每个角的边框重叠

lan*_*224 8 flutter

我制作了一个容器,该容器应该显示周围有彩色边框的图片,并添加 borderRadius 将其设置为 8,但是后来我注意到,当我设置容器来剪辑内容时,它会使边框角褪色,如下所示:

内容重叠边框角

我是这样写的

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,
            ),
          ),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望内容不与我的边框重叠,该怎么做?

Roh*_*ker 17

我希望内容不与我的边框重叠,该怎么做?

为了实现这一点,您需要设置 的foregroundDecorationdecoration属性Container,两者之间的区别在于,将在子项前面绘制foregroundDecoration装饰并在子项后面绘制,这就是为什么您在使用时会得到剪裁decorationdecoration

注意foregroundDecoration使用 a设置clipBehavior将触发一个AssertionError,因为clipBehavior必须使用 a 指定decoration

将代码更新为以下内容,以获得所需的效果:

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

Run Code Online (Sandbox Code Playgroud)

容器上前景装饰的预览