Do you want to create a transparent container in flutter? If yes then you have come to the right place. In our example, you will learn how to create a transparent container in a flutter.
Step 1: Create a Sample Container
The first step is to create a Container. You can use create Container in flutter using the Container() class. Let’s create a Container.
Container(
width: 200,
height: 200,
color: Color(0xFFE44336)
),

Step 2: Create a transparent container
The next step is to create a transparent container . You can do so by using the withOpacity() method for the color. Here you have to use the below syntax.
Color(#yourhexcolorcode).withOpacity(value)
color: Color(0xFFE44336).withOpacity(0.5)
The above line of code will make the container 50% transparent. Below is the full code.
import 'package:flutter/material.dart';
class MyApp extends StatefulWidget {
// This widget is the root of your application.
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State {
@override
Widget build(BuildContext context) {
return MaterialApp(
// Application name
title: 'My Flutter App',
debugShowCheckedModeBanner: false, // Remove debug banner
home: Scaffold(
appBar: AppBar(
// The title text which will be shown on the action bar
title: Text("My Flutter App"),
),
body: Center(
child: Container(
width: 200,
height: 200,
color: Color(0xFFE44336).withOpacity(0.5)),
),
),
);
}
}
void main() {
runApp(MyApp());
}
Output

Let’s implement some good examples of the transparent container in a flutter. Suppose I have one container with text in it and another container above it. if you want to see the text written on the below container you have to make the above container transparent.
In this case, you have to use a flutter stack widegt for creating one container the above. Execute the below lines of code.
import 'package:flutter/material.dart';
class MyApp extends StatefulWidget {
// This widget is the root of your application.
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State {
@override
Widget build(BuildContext context) {
return MaterialApp(
// Application name
title: 'My Flutter App',
debugShowCheckedModeBanner: false, // Remove debug banner
home: Scaffold(
appBar: AppBar(
// The title text which will be shown on the action bar
title: Text("My Flutter App"),
),
body: Center(
child: Stack(
alignment: Alignment.center,
children: [
Container(
alignment: Alignment.center,
width: 200,
height: 200,
child: Text(
"Code the best",
style: TextStyle(color: Colors.white, fontSize: 20),
),
color: Color(0xFFE44336),
),
Container(
width: 300,
height: 400,
color: Colors.black.withOpacity(0.1),
)
],
),
),
),
);
}
}
void main() {
runApp(MyApp());
}
You cannot see the text without opacity.

But when you transparent the second container, you will see the text.

Leave a Reply