How to set Transparent Background Color in Flutter

In this example, we are going to show you how to add semi-transparent background color on AppBar, Container, and to any other widget in the Flutter app. See the example, and learn different methods to add a background color with opacity.

Container( 
  color: Colors.redAccent.withOpacity(0.5)
)

You can use Colors.colorName.withOpacity(opacity) method to set the transparent background color. Here, 0.5 is an opacity value, which ranges from 0-1.

AppBar( 
  backgroundColor: Color.fromRGBO(24,233, 111, 0.6),
)

You can use Color.fromRGBO(Red, Green, Blue, Opacity) method to set the transparent background color. 

Container( 
   color: Color.fromARGB(100, 22, 44, 33),
)

You can use Color.fromARGB(Alpha, Red, Green, Blue) method to set the transparent background color. The alpha value ranges from 0-255.

Opacity( 
    opacity: 0.5, //from 0-1, 0.5 = 50% opacity
    child:Container(
        //widget tree
    )
)

You can wrap your widget tree with Opacity() widget, it will set the opacity to your widget including its content.

import 'package:flutter/material.dart';

void main(){
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget{
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return  Scaffold(
          appBar: AppBar( 
             title: Text("Transparent Background Color"),
             backgroundColor: Colors.redAccent.withOpacity(0.5),
                              //0.5 is transparency 
          ),
          body: Container(
             color: Colors.redAccent,
             child: Stack( 
                 children: [
                     Image.asset("assets/images/elephant.jpg"),
                     Container( 
                        width: double.infinity,
                        color: Color.fromARGB(100, 22, 44, 33),
                        margin: EdgeInsets.all(20),
                        padding: EdgeInsets.all(40),
                        child: Text("Hello Everyone! This is FlutterCampus",
                             style: TextStyle(fontSize: 25, color: Colors.white),),
                     ),
                 ],
             ),
          )
       );
  }
}

Here, we have made an overlapping widgets tree where the Image is set at the bottom and another container at top of the image with transparent background. The output of the above code will look like below:

In this way, you can set the semi-transparent background color on AppBar, Container widget in Flutter App.

No any Comments on this Article


Please Wait...