Introduction to the
Opacity: Changes the Opacity of a Child Widget.
Opacity( opacity: ... , child: Text(" hehe "),)Copy the code
The value of the opacity property ranges from 0.0 to 1.0. 0 means completely transparent, 1 means completely opaque. You can also use Opacity to hide and display widgets.
The sample
class TestUi extends StatefulWidget {
const TestUi({Key key}) : super(key: key);
@override
_TestUiState createState() => _TestUiState();
}
class _TestUiState extends State<TestUi> {
/// Transparency ranges from 0.0 to 1.0
var _opacity = 0.0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Change transparency',style: TextStyle(fontSize: )),
),
body: Container(
child: Column(
children: [
Opacity(
opacity: _opacity,
child: Center(child: Text("Ha ha")),
),
Slider(
value: _opacity,
min: 0.0,
max: 1.0,
onChanged: (value) {
/// Transparency is controlled by a slidersetState(() { _opacity = value; }); }),],),); }}Copy the code
Performance Suggestions
The official advice is not to use Opacity unless absolutely necessary. Because Opacity draws content to an off-screen buffer, it could trigger a switch to the render target. On older devices, gpus can be extremely slow.
Only change the color transparency
If you just want to change the Opacity of an Image or color, you don’t need to use Opacity at all. Use RGB to change the transparency.
The sample
Container(/// The last parameter stands for opacity color: color.froMRGbo (255, 22, 33, _opacity), Child: Text(" Change the opacity of the background color "),), Slider(value: _opacity, min: 0.0, Max: 1.0, onChanged: (value) {setState(() {_opacity = value; }); }),Copy the code
AnimatedOpacity
If the Opacity needs to be changed frequently, you are advised to use AnimatedOpacity for better performance. Each time the transparency changes, there will be a transition effect, so the change will not feel stiff.
AnimatedOpacity( opacity: _opacity, duration: Duration(milliseconds: 500), child: Center( child: Text( "Hello,world!" , style: TextStyle(fontSize: 30),)),), Slider(value: _opacity, min: 0.0, Max: 1.0, onChanged: (value) { setState(() { _opacity = value; }); }),Copy the code