我正在使用Flutter,我想向小部件(在本例中是文本小部件)添加边框。

我尝试了TextStyle和文本,但我不知道如何添加边框。


当前回答

文本边框样式:

Stack(
  children: <Widget>[
    // Stroked text as border.
    Text(
      'Greetings, planet!',
      style: TextStyle(
        fontSize: 40,
        foreground: Paint()
          ..style = PaintingStyle.stroke
          ..strokeWidth = 6
          ..color = Colors.blue[700]!,
      ),
    ),
    // Solid text as fill.
    Text(
      'Greetings, planet!',
      style: TextStyle(
        fontSize: 40,
        color: Colors.grey[300],
      ),
    ),
  ],
)

其他回答

在这里,由于Text小部件没有允许我们定义边框的属性,我们应该用一个允许我们定义边框的小部件来包装它。 有几种解决方案。 但是最好的解决方案是在容器小部件中使用BoxDecoration。

为什么选择使用BoxDecoration?

因为BoxDecoration提供了更多的定制,比如定义:

首先,边界和也定义:

边框颜色 边框宽度 边界半径 形状 还有更多……

一个例子:

   Container(
     child:Text(' Hello Word '),
     decoration: BoxDecoration(
          color: Colors.yellow,
          border: Border.all(
                color: Colors.red ,
                width: 2.0 ,
              ),
          borderRadius: BorderRadius.circular(15),
            ),
          ),

输出:

最好的方法是使用BoxDecoration()

优势

您可以设置小部件的边框 你可以设置边框的颜色或宽度 您可以设置边框的圆角 您可以添加一个小部件的影子

缺点

BoxDecoration只与容器小部件一起使用,所以你需要将小部件包装在Container()中

例子

    Container(
      margin: EdgeInsets.all(10),
      padding: EdgeInsets.all(10),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colors.orange,
        border: Border.all(
            color: Colors.pink[800], // Set border color
            width: 3.0),   // Set border width
        borderRadius: BorderRadius.all(
            Radius.circular(10.0)), // Set rounded corner radius
        boxShadow: [BoxShadow(blurRadius: 10,color: Colors.black,offset: Offset(1,3))] // Make rounded corner of border
      ),
      child: Text("My demo styling"),
    )

文本边框样式:

Stack(
  children: <Widget>[
    // Stroked text as border.
    Text(
      'Greetings, planet!',
      style: TextStyle(
        fontSize: 40,
        foreground: Paint()
          ..style = PaintingStyle.stroke
          ..strokeWidth = 6
          ..color = Colors.blue[700]!,
      ),
    ),
    // Solid text as fill.
    Text(
      'Greetings, planet!',
      style: TextStyle(
        fontSize: 40,
        color: Colors.grey[300],
      ),
    ),
  ],
)

上面的答案也是正确的,但是如果您想在同一个小部件上添加多个边框,那么您可以设置这个选项

Container(
      child: const Center(
        child: Text(
          'This is your Container',
        ),
      ),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.white,
        boxShadow: const [
          BoxShadow(color: Colors.green, spreadRadius: 8),
          BoxShadow(color: Colors.yellow, spreadRadius: 5),
        ],
      ),
      height: 50,
    )

如果有人想要一个概述/边界文本或应用多个边界。

你可以试试这个:

https://pub.dev/packages/outlined_text

DEMO