Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

flutter - Container borderRadius vs ClipRRect borderRadius

Both Container and ClipRRect has borderRadius property, but sometimes Container fail to work. Here is the example.

Not working

Container(
  decoration: BoxDecoration(borderRadius: BorderRadius.circular(100)),
  child: RaisedButton(onPressed: null),
),

Working

ClipRRect(
  borderRadius: BorderRadius.circular(100),
  child: RaisedButton(onPressed: null),
),

I want to know why Container fails sometimes and where else it can fail?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

ClipRRect inserts a render object that modifies the render tree of the widgets in its subtree.

Subtree of ClipRRect will be affected and the corners will be clipped.

Hit tests for the widget itself as well as for its children will be performed with the clip path respected. Meaning that gesture recognizers (/ buttons) within the widget will not receive taps outside of the clipped area.

ClipRRect is relatively expensive, but is suitable to clip an image or other complex graphic elements that do not provide rounded corners setting on their own.


Container on the other hand, when used with BoxDecoration and borderRadius / shape set, simply draws a box with rounded corners on its background.

Subtree of such Container will not be affected by the background decoration of their parent widget.

Hit tests for the Container will be performed with borderRadius respected, providing "truly rounded" UI-wise tap experience for the container itself. However, children gesture recognizers are not exposed to the decoration settings - hence, gestures will be received as usual even beyond the "clipped" area.

Decorated container with shape or borderRadius set is preferable as it is relatively less expensive to draw and maintain, given that the clipping mask for the subtree is not needed.


In the end, I do have to note that neither way described here is the best way in your case.

To create a RaisedButton with rounded corners use RoundedRectangleBorder for the shape property of your button.

e.g.

RaisedButton(
  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(100))
  // ...,
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...