In this tutorial, we are going to show you how to set opacity of any widget in Flutter, including how to set the initial opacity and update the opacity value.
Sometimes, we want to make a widget looks more transparent by setting opacity. In Flutter, it can be done easily by using Opacity
widget. Here are the options you can use in the constructor.
Option | Description |
---|---|
Key key |
The Opacity widget's key. |
double opacity (required) |
Alpha value of the child . |
boolean alwaysIncludeSemantics |
Whether the semantic information of the children is always included. |
Widget child |
The widget whose opacity will be controlled. |
The opacity value must be between 0.0 and 1.0 (inclusive). At value 0.0, the child
looks invisible (transparency is 100%). At 1.0, the transparency is 0%.
Code Example
Below is an example how to use the Opacity
widget. In this example, there is a button whose opacity is set to 0.5 at the beginning. Tap it to adjust the opacity value. To make it possible to update the value, it's stored as a state.
import 'package:flutter/material.dart';
class OpacityExample extends StatefulWidget {
@override
_OpacityExampleState createState() {
return _OpacityExampleState();
}
}
class _OpacityExampleState extends State<OpacityExample> {
double _opacity = 0.5;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Opacity Tutorial',
home: Scaffold(
appBar: AppBar(
title: Text('Opacity Tutorial'),
),
body: Padding(
padding: EdgeInsets.all(15.0),
child: Center(
child: Opacity(opacity: _opacity,
child: RaisedButton(
child: Text('Woolha.com'),
onPressed: () {
setState(() {
double newOpacity = _opacity + 0.5;
_opacity = newOpacity > 1 ? 0 : newOpacity;
});
},
),
),
),
)
),
);
}
}
void main() => runApp(OpacityExample());