Adding shadows to widgets in Flutter - flutter

I was trying to add a border shadow effect to a Container in a way that resembles exactly the same design as in the picture below. My initial idea was of using the CustomPaint class feature to do so. However, it hasn't worked out the way I wanted it to. I would honestly like to know how this can be achieved through the use of the CustomPaint class and I apologize for the code that I've written as I'm still trying to get used to CustomPaint. The code and the pictures are as follows:
This is what I intend to achieve:
This is what I have. You can see that the border goes well beyond where it should be and also, the border at the bottom gets clipped and despite adjusting the bottom padding:
This is the code:
class ProfilePageState extends State<ProfilePage> {
#override
Widget build(BuildContext context) {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
overlays: [SystemUiOverlay.bottom]);
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
final textScale = MediaQuery.of(context).textScaleFactor * 1.2;
// TODO: implement build
return Scaffold(
body: ListView(
children: [
Container(
height: height * 1,
width: width * 1,
// color: Colors.red,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/filter.png'),
fit: BoxFit.cover)),
child: Column(
......
Padding(
padding: EdgeInsets.only(left: width * 0.035),
child: Container(
width: double.infinity,
height: height * 0.25,
padding: EdgeInsets.only(
left: width * 0.03,
top: height * 0.01,
// bottom: height * 0.01
),
// color: Colors.yellow,
child: ProfilePageFavourite(), //This here is the widget
),
),
],
),
),
],
),
);
}
}
The ProfilePageFavourite widget:
class ProfilePageFavouriteState extends State<ProfilePageFavourite> {
// final List<dynamic> _favouritesList = [
// ];
var favourite = false;
void _onPressed() {
setState(() => favourite = !favourite);
print(favourite);
}
#override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
final height = MediaQuery.of(context).size.height;
final textScale = MediaQuery.of(context).textScaleFactor * 1.2;
// TODO: implement build
return ListView.builder(
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) => Stack(
children: [
CustomPaint( //This is where I try using the CustomPaint class
painter: OrangePainter(),
child: Container(
width: width * 0.75,
margin: EdgeInsets.only(right: width * 0.09),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.yellow,
image: DecorationImage(
fit: BoxFit.fitWidth,
image: AssetImage('assets/images/pub screen 1 (1).png'))),
),
),
Positioned(
top: height * 0.16,
child: Container(
height: height * 0.07,
width: width * 0.75,
padding: EdgeInsets.only(top: height * 0.008),
decoration: BoxDecoration(
color: Colors.black38,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(20),
bottomRight: Radius.circular(20))),
child: Column(
children: [
Row(
// mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
padding: EdgeInsets.only(left: width * 0.05),
decoration: BoxDecoration(boxShadow: [
BoxShadow(
color: Colors.red,
blurRadius: 35,
spreadRadius: 8,
offset: Offset(0, 2))
]),
child: Image.asset(
'assets/icons/dine.png',
color: Colors.white,
),
),
SizedBox(
width: width * 0.02,
),
Text(
'Sollicitudin',
textScaleFactor: textScale,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20,
shadows: [
Shadow(
color: Colors.red,
blurRadius: 10,
offset: Offset(0, 2))
]),
)
],
),
Container(
width: double.infinity,
// color: Colors.red,
padding: EdgeInsets.only(left: width * 0.118),
child: CustomRatingBar(4.5))
],
),
),
),
Positioned(
left: width * 0.58,
top: height * 0.01,
child: Container(
decoration: BoxDecoration(boxShadow: [
BoxShadow(
color: Colors.pink,
blurRadius: 80,
spreadRadius: 6,
)
]),
child: !favourite
? IconButton(
onPressed: _onPressed,
icon: Icon(
Icons.favorite,
// color: Color.fromRGBO(247, 180, 230, 0.8),
color: Colors.pink,
size: 50,
))
: IconButton(
onPressed: _onPressed,
icon: Icon(
Icons.favorite_border_outlined,
color: Colors.pink,
size: 50,
)),
),
),
],
),
itemCount: 5,
);
}
}
The CustomPaint Class
class OrangePainter extends CustomPainter {
OrangePainter();
#override
void paint(Canvas canvas, Size size) {
final rrectBorder =
RRect.fromRectAndRadius(Offset.zero & size, Radius.circular(12));
final rrectShadow =
RRect.fromRectAndRadius(Offset(0, 2) & size, Radius.circular(12));
final shadowPaint = Paint()
..color = Colors.lightGreen
..style = PaintingStyle.stroke
..strokeWidth = 3
..maskFilter = MaskFilter.blur(BlurStyle.solid, 20);
canvas.drawRRect(rrectShadow, shadowPaint);
}
#override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
// TODO: implement shouldRepaint
return true;
}
}

I would like to suggest an alternative approach, Custom Paint is very expensive to use in applications. You could instead wrap your container in a Card() then add your shadowColor: Colors.lightGreen set the **shape: ** to the same as your Container() and you should get the result you desire

I have retained the initial customPaint and used it here.This code combines your ProfilePageState and ProfilePageFavourite to give you the appearance below. I've just built it on my phone's dartpad so you can do the editing so it matches. I included comments:
#override
Widget build(BuildContext context) {
return Scaffold(
body: SizedBox(
height: 250,
width: double.infinity,
child: ListView.separated(
scrollDirection: Axis.horizontal,
itemCount: 5,
separatorBuilder: (ctx, index) => const SizedBox(width: 10),
itemBuilder: (ctx, index) => ClipRRect(
child: CustomPaint(
painter: OrangePainter(),
child: Container(
padding: const EdgeInsets.symmetric(horizontal:10,vertical:15),//increase padding to your liking
width: 350,
decoration: BoxDecoration(
// image: DecorationImage(image: AssetImage('')), add your image here and remove color below
color: Colors.black54,
borderRadius: BorderRadius.circular(10),
),
child: Column(
mainAxisAlignment:MainAxisAlignment.spaceBetween,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: const [
Icon(Icons.favorite, size: 40),
],
),
Row(
children: [
const Icon(Icons.restaurant),
const SizedBox(width:10),
Column(
children: const [
Text(
'Sollicitudin',
// textScaleFactor: textScale,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20,
shadows: [
Shadow(
color: Colors.red,
blurRadius: 10,
offset: Offset(0, 2))
],
),
),
Icon(Icons.star),//Replace with your CustomRation()
],
),
],
),
],
),
),
),
),
),
),
);
}
}
class OrangePainter extends CustomPainter {
OrangePainter();
#override
void paint(Canvas canvas, Size size) {
final rrectBorder =
RRect.fromRectAndRadius(Offset.zero & size, const Radius.circular(12));
final rrectShadow =
RRect.fromRectAndRadius(const Offset(0, 2) & size, const Radius.circular(12));
final shadowPaint = Paint()
..color = Colors.lightGreen
..style = PaintingStyle.stroke
..strokeWidth = 3
..maskFilter = MaskFilter.blur(BlurStyle.solid, 20);
canvas.drawRRect(rrectShadow, shadowPaint);
}
#override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
// TODO: implement shouldRepaint
return true;
}
}

Related

How to create a scrollable expandable list with a custom clipped container?

I am trying to recreate this UI:
Collapsed
Expanded
I first created the custom container shape using a ClipPath with a CustomClipper:
class FolderClipper extends CustomClipper<Path> {
#override
Path getClip(Size size) {
Path path = Path();
Offset c1 = Offset(size.width * .0825, size.height * .048);
Offset c2 = Offset(size.width * .021, size.height * .0075);
Offset end = Offset(size.width * .12, size.height * 0);
path.moveTo(0, size.height * 0.0775);
path.cubicTo(c1.dx, c1.dy, c2.dx, c2.dy, end.dx, end.dy);
path.lineTo(size.width * .71, end.dy);
Offset c1_2 = Offset(size.width * .829, size.height * .0002);
Offset c2_2 = Offset(size.width * .7497, size.height * .06495);
Offset end_2 = Offset(size.width * .8602, size.height * .0652);
path.cubicTo(c1_2.dx, c1_2.dy, c2_2.dx, c2_2.dy, end_2.dx, end_2.dy);
path.lineTo(size.width, end_2.dy);
path.lineTo(size.width, size.height);
path.lineTo(0, size.height);
path.close();
return path;
}
#override
bool shouldReclip(covariant CustomClipper<Path> oldClipper) {
return false;
}
This draws the shape as expected when it takes up the full screen:
#override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.only(top: 16.0),
child: ClipPath(
clipper: FolderClipper(),
child: Container(
height: MediaQuery.of(context).size.height,
decoration: const BoxDecoration(
color: Colors.grey,
),
child: const Center(
child: Text('Text'),
),
),
),
),
);
shape drawn with a large height
Approach 1
To put this shape into an expandable list, I used the containers with different content (child) in a CustomScrollView.
I had to use a collapsed and expanded container, which will basically be the same custom clipped container that I created earlier in the full screen, except the expanded one will have the grid of cards. I set a height when the container is in the collapsed state because otherwise it won't show if it has no children (and if I add a child that takes a large space, the collapsed item will take up a large height, which is not what I want). Setting that height however distorts the shape and so it doesn't look right (it only looks right when it has a relatively large height). I put the custom shape in a stack and added a container with a color that matches the preceding container's color under it so that it looks as if it's stacked.
Issues:
Given different heights, the custom shape becomes distorted and does not have the same proportions (the curves don't look the same for different heights).
There are lines that appear between widgets (same colored widgets that touch) that I think might be a bug in flutter (I'm using flutter 2.10.4 and it will be difficult to upgrade). I think these lines are due to the height and pixel density not quite matching and so the background can be seen.
[kinda worked] I tried to fix this by using Transform.translate with a y-axis offset of -8 on the background container that has the color of the preceding list item. This seems to work for the most part (since I don't care about the bottom of the container being shifted up). This however doesn't fix the elevation issue (issue #3).
I also tried to fix this by adding a similar CustomScrollView below the current one so that the background color would always match the expandable panel, but how will I know the size of the panel when it expands so that the scrollview with the background colors would match (I had their scroll controllers linked), but that wasn't the best and added complexity.
The elevation is not working on the last item (which is supposed to be an inverse-ish shape that I haven't done yet, I'm just reusing the shape I have to test it out). I added a border to try and make it more prominent, but that background line (between same colored widgets) is messing things up.
In general the shadow/elevation for each item in the list was not showing. I tried wrapping the container in a Material widget and gave it an elevation and I also tried using BoxShadow.
Here's what the code looks like after my fix attempts:
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'folder_clipper.dart';
import 'folder_clipper2.dart';
class MyAttempt extends StatelessWidget {
MyAttempt({Key? key}) : super(key: key);
RxInt _selectedIndex = (-1).obs;
final List<Color> colors = [
Color(0xFFBDBDBD),
Colors.grey,
Color(0xFF757575)
];
final int optionsCount = 5;
final int gridOptionCount = 2;
ScrollController sc = ScrollController();
//ScrollController scBack = ScrollController();
#override
Widget build(BuildContext context) {
// sc.addListener(() {
// scBack.jumpTo(sc.offset);
// });
return Padding(
padding: const EdgeInsets.only(top: 16.0),
child: Stack(
children: [
// CustomScrollView(
// controller: sc,
// slivers: [
// SliverList(
// delegate: SliverChildBuilderDelegate(
// (BuildContext context, int index) {
// return Container(
// decoration: BoxDecoration(
// color: index == 0
// ? Colors.transparent
// : colors[(index - 1) % colors.length],
// ),
// width: double.infinity,
// height: _selectedIndex.value == index
// ? null
// : (Get.height * .1),
// child: Obx(() => _selectedIndex.value == index
// ? gridView(index)
// : const SizedBox.shrink()),
// );
// },
// childCount: optionsCount,
// ),
// ),
// SliverFillRemaining(
// child: GestureDetector(
// onTap: () {
// if (_selectedIndex.value == 2)
// _selectedIndex.value = -1;
// else
// _selectedIndex.value = 2;
// },
// child: Stack(
// children: [
// Container(
// color: colors[(optionsCount - 1) % colors.length],
// width: double.infinity,
// ),
// ClipPath(
// clipper: FolderClipper2(),
// child: Material(
// elevation: 10,
// child: Container(
// decoration: BoxDecoration(
// color: colors[(optionsCount - 1) % colors.length],
// border: const Border(
// top:
// BorderSide(width: 1.0, color: Colors.black),
// ),
// ),
// ),
// ),
// ),
// ],
// ),
// ),
// )
// ],
// ),
CustomScrollView(
controller: sc,
slivers: [
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Stack(
children: [
Transform.translate(
offset: Offset(0, -8),
child: Container(
decoration: BoxDecoration(
color: index == 0
? Colors.transparent
: colors[(index - 1) % colors.length],
),
width: double.infinity,
height: ((Get.height * .1)),
),
),
ClipPath(
clipper: FolderClipper(),
child: Material(
child: GestureDetector(
onTap: () {
if (_selectedIndex.value == index) {
_selectedIndex.value = -1;
} else {
_selectedIndex.value = index;
}
},
child: Obx(
() => Stack(
children: [
Container(
decoration: BoxDecoration(
color: colors[index % colors.length],
),
height: _selectedIndex.value != index
? (Get.height * .1)
: null,
width: double.infinity,
child: Obx(() =>
_selectedIndex.value == index
? gridView(index)
: const SizedBox.shrink()),
),
Container(
margin: EdgeInsets.only(
top: Get.height * .025,
left: Get.width * .125),
child: Text(
"Option $index",
style: const TextStyle(
fontWeight: FontWeight.bold),
),
),
],
),
),
),
),
),
],
);
},
childCount: optionsCount,
),
),
SliverFillRemaining(
child: Stack(
children: [
Transform.translate(
offset: Offset(0, -8),
child: Container(
color: colors[(optionsCount - 1) % colors.length],
width: double.infinity,
),
),
ClipPath(
clipper: FolderClipper2(),
child: Material(
elevation: 10,
child: Container(
decoration: BoxDecoration(
boxShadow: const [
BoxShadow(
color: Colors.black,
spreadRadius: 5,
blurRadius: 5,
offset:
Offset(0, -8), // changes position of shadow
),
],
color: colors[(optionsCount - 1) % colors.length],
border: const Border(
top: BorderSide(width: 1.0, color: Colors.black),
),
),
),
),
),
],
),
)
],
),
],
),
);
}
gridView(index) {
return GridView.count(
shrinkWrap: true,
primary: true,
padding: EdgeInsets.only(
left: Get.width * .15,
right: Get.width * .15,
top: Get.width * .15,
bottom: 16),
crossAxisSpacing: Get.width * .075, //24,
mainAxisSpacing: Get.width * .075, //16,
crossAxisCount: 2,
children: <Widget>[
for (int i = 0; i < (gridOptionCount * index); i++)
Card(
elevation: 10,
child: Container(
//width: Get.width * .05,
//height: Get.width * .05,
color: Colors.white,
child: Center(
child: Container(
child: Text(
"option $i",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
)),
),
],
);
}
}
and here is what it looks like, it's kind of working, but doesn't look right mainly due to the CustomClipper being distorted due to the height of the container and the shadows not working as expected:
collapsed state
expanded state
Approach 2
To put this shape into an expandable list, I used the expandable package on pub.dev in a CustomScrollView.
I set a header and expanded widget, which will basically be the same custom clipped container that I created, except the expanded one will have the grid of cards. I set a height when the container is in the header only state because otherwise it will be so short if it has no children (and if I add a child that takes a large space, the collapsed item will take up a large height, which is not what I want). Setting that height however distorts the shape and so it doesn't look right (it only looks right when it has a relatively large height). I put the custom shape in a stack and added a container with a color that matches the preceding container's color under it so that it looks as if it's stacked. I did not use the collapsed widget (set it to SizedBox.shrink).
Here's the code:
import 'package:expandable/expandable.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'folder_clipper.dart';
import 'folder_clipper2.dart';
class MyAttempt2 extends StatelessWidget {
MyAttempt2({Key? key}) : super(key: key);
RxInt _selectedIndex = (-1).obs;
final List<Color> colors = [
Color(0xFFBDBDBD),
Colors.grey,
Color(0xFF757575)
];
final int optionsCount = 5;
final int gridOptionCount = 2;
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 16.0),
child: CustomScrollView(
slivers: [
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Stack(
children: [
ExpandableNotifier(
child: Stack(
children: [
Transform.translate(
offset: Offset(0, -8),
child: Container(
decoration: BoxDecoration(
color: index == 0
? Colors.transparent
: colors[(index - 1) % colors.length],
),
width: double.infinity,
height: ((Get.height * .1)),
),
),
ClipPath(
clipper: FolderClipper(),
child: Container(
//height: MediaQuery.of(context).size.height,
decoration: BoxDecoration(
color: colors[index % colors.length],
),
child: ScrollOnExpand(
scrollOnExpand: true,
scrollOnCollapse: false,
child: ExpandablePanel(
theme: const ExpandableThemeData(
headerAlignment:
ExpandablePanelHeaderAlignment.center,
tapBodyToCollapse: true,
),
header: Container(
height: ((Get.height * .1)),
child: Padding(
padding: EdgeInsets.all(10),
child: Text(
"ExpandablePanel",
style: Theme.of(context)
.textTheme
.bodyText2,
)),
),
collapsed: SizedBox.shrink(),
// Text(
// loremIpsum,
// softWrap: true,
// maxLines: 2,
// overflow: TextOverflow.ellipsis,
// ),
expanded: SingleChildScrollView(
child: gridView(index)),
builder: (_, collapsed, expanded) {
return Padding(
padding: EdgeInsets.only(
left: 0, right: 0, bottom: 0),
child: Expandable(
collapsed: collapsed,
expanded: expanded,
theme: const ExpandableThemeData(
crossFadePoint: 0),
),
);
},
),
),
),
//margin: EdgeInsets.zero,
//clipBehavior: Clip.antiAlias,
),
],
),
),
],
);
},
childCount: optionsCount,
),
),
SliverFillRemaining(
child: Stack(
children: [
Container(
color: colors[(optionsCount - 1) % colors.length],
width: double.infinity,
),
ClipPath(
clipper: FolderClipper2(),
child: Material(
elevation: 10,
child: Container(
decoration: BoxDecoration(
boxShadow: const [
BoxShadow(
color: Colors.black,
spreadRadius: 5,
blurRadius: 5,
offset: Offset(0, -8), // changes position of shadow
),
],
color: colors[(optionsCount - 1) % colors.length],
border: const Border(
top: BorderSide(width: 1.0, color: Colors.black),
),
),
),
),
),
],
),
)
],
),
);
}
gridView(index) {
return GridView.count(
shrinkWrap: true,
primary: true,
padding: EdgeInsets.only(
left: Get.width * .15,
right: Get.width * .15,
top: Get.width * .15,
bottom: 16),
crossAxisSpacing: Get.width * .075, //24,
mainAxisSpacing: Get.width * .075, //16,
crossAxisCount: 2,
children: <Widget>[
for (int i = 0; i < (gridOptionCount * index); i++)
Card(
elevation: 10,
child: Container(
//width: Get.width * .05,
//height: Get.width * .05,
color: Colors.white,
child: Center(
child: Container(
child: Text(
"option $i",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
)),
),
],
);
}
}
and this is what it looks like:
collapsed (header only) state
expanded state
Similar issues as approach 1.
UPDATE
I managed to add a height factor to the CustomClipper so that all offsets are relative to the height I based it off of and that seemed to get the shape to be consistent! Will probably do the same for the width.
Here's the new code:
class FolderClipper extends CustomClipper<Path> {
#override
Path getClip(Size size) {
print("${size.width} - ${size.height}");
double heightFactor = size.height / 667;
double widthFactor = size.width / 375;
Path path = Path();
Offset c1 = Offset(size.width * .0825, size.height * .048);
Offset c2 = Offset(size.width * .021, size.height * .0075);
Offset end = Offset(size.width * .12, size.height * 0);
// if (size.height < 100)
// path.moveTo(0, size.height * .5);
// else if (size.height < 300)
// path.moveTo(0, size.height * .15);
// else
path.moveTo(0, size.height * 0.0775 / heightFactor);
path.cubicTo(c1.dx, c1.dy / heightFactor, c2.dx, c2.dy / heightFactor,
end.dx, end.dy / heightFactor);
path.lineTo(size.width * .71, end.dy / heightFactor);
Offset c1_2 = Offset(size.width * .829, size.height * .0002);
Offset c2_2 = Offset(size.width * .7497, size.height * .06495);
Offset end_2;
// if (size.height < 100)
// end_2 = Offset(size.width * .8602, size.height * .45);
// else if (size.height < 300)
// end_2 = Offset(size.width * .8602, size.height * .15);
// else
end_2 = Offset(size.width * .8602, size.height * .0652);
path.cubicTo(c1_2.dx, c1_2.dy / heightFactor, c2_2.dx,
c2_2.dy / heightFactor, end_2.dx, end_2.dy / heightFactor);
path.lineTo(size.width, end_2.dy / heightFactor);
path.lineTo(size.width, size.height);
path.lineTo(0, size.height);
path.close();
return path;
}
#override
bool shouldReclip(covariant CustomClipper<Path> oldClipper) {
return false;
}
This is what it looks like now:
expanded state - issue with SliverFillRemaining line on top and shadows
So I believe the main issue remaining here is with the shadow and the space between the last item and the SliverFillRemainingSection (and its shadow as well)

How to modify the position of the text and the listview?

I'm trying to make a music app and I'm in trouble with modifying positions of 'Playlist of the week' text and the Listview of the images right now. I want to make those two properties more upwards but I have no idea what to do.
This is my home.dart file
import 'package:flutter/material.dart';
import 'package:secondlife_mobile/PageViewHolder.dart';
import 'package:provider/provider.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final PageStorageBucket bucket = PageStorageBucket();
late PageViewHolder holder;
late PageController _controller;
double fraction =
0.57; // By using this fraction, we're telling the PageView to show the 50% of the previous and the next page area along with the main page
#override
void initState() {
super.initState();
holder = PageViewHolder(value: 2.0);
_controller = PageController(initialPage: 2, viewportFraction: fraction);
_controller.addListener(() {
holder.setValue(_controller.page);
});
}
int index = 1;
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: const Color.fromARGB(255, 223, 234, 244),
appBar: AppBar(
backgroundColor: Colors.transparent,
centerTitle: true,
title: const Text('AppBar'),
),
body: SingleChildScrollView(
child: SizedBox(
height: MediaQuery.of(context).size.height,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
height: 30,
),
const Padding(
padding: EdgeInsets.symmetric(horizontal: 35),
child: Text(
'Playlist for you',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w400,
),
),
),
const SizedBox(height: 35),
Container(
child: Center(
child: AspectRatio(
aspectRatio: 1,
child: ChangeNotifierProvider<PageViewHolder>.value(
value: holder,
child: PageView.builder(
controller: _controller,
itemCount: 4,
physics: const BouncingScrollPhysics(),
itemBuilder: (context, index) {
return MyPage(
number: index.toDouble(),
fraction: fraction,
);
}),
),
),
),
),
////Your Playlist of the week text
const Padding(
padding: EdgeInsets.symmetric(horizontal: 35),
child: Text(
'Playlist of the week',
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.w600,
),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 35),
child: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 150,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
InkWell(
onTap: () {},
child: Ink(
child: SizedBox(
height: 160.0,
width: 200.0,
child: Image.asset(
'assets/images/album1.jpg',
height: 160.0,
width: 200.0,
),
),
),
),
const SizedBox(
width: 30,
),
InkWell(
onTap: () {},
child: Ink(
child: SizedBox(
height: 160.0,
width: 200.0,
child: Image.asset(
'assets/images/album2.jpg',
height: 160.0,
width: 200.0,
),
),
),
),
const SizedBox(
width: 30,
),
InkWell(
onTap: () {},
child: Ink(
child: SizedBox(
height: 160.0,
width: 200.0,
child: Image.asset(
'assets/images/album3.jpg',
height: 160.0,
width: 200.0,
),
),
),
),
const SizedBox(
width: 30,
),
InkWell(
onTap: () {},
child: Ink(
child: SizedBox(
height: 160.0,
width: 200.0,
child: Image.asset(
'assets/images/album4.jpg',
height: 160.0,
width: 200.0,
),
),
),
),
const SizedBox(
width: 30,
),
InkWell(
onTap: () {},
child: Ink(
child: SizedBox(
height: 160.0,
width: 200.0,
child: Image.asset(
'assets/images/album5.jpg',
height: 160.0,
width: 200.0,
),
),
),
),
],
),
),
],
),
),
),
],
),
),
),
),
);
}
}
class MyPage extends StatelessWidget {
final number;
final double? fraction;
const MyPage({super.key, this.number, this.fraction});
#override
Widget build(BuildContext context) {
double? value = Provider.of<PageViewHolder>(context).value;
double diff = (number - value);
// diff is negative = left page
// diff is 0 = current page
// diff is positive = next page
//Matrix for Elements
final Matrix4 pvMatrix = Matrix4.identity()
..setEntry(3, 2, 1 / 0.9) //Increasing Scale by 90%
..setEntry(1, 1, fraction!) //Changing Scale Along Y Axis
..setEntry(3, 0, 0.004 * -diff); //Changing Perspective Along X Axis
final Matrix4 shadowMatrix = Matrix4.identity()
..setEntry(3, 3, 1 / 1.6) //Increasing Scale by 60%
..setEntry(3, 1, -0.004) //Changing Scale Along Y Axis
..setEntry(3, 0, 0.002 * diff) //Changing Perspective along X Axis
..rotateX(1.309); //Rotating Shadow along X Axis
return Stack(
fit: StackFit.expand,
alignment: FractionalOffset.center,
children: [
Transform.translate(
offset: const Offset(0.0, -47.5),
child: Transform(
transform: pvMatrix,
alignment: FractionalOffset.center,
child: Container(
decoration: BoxDecoration(boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
blurRadius: 11.0,
spreadRadius: 4.0,
offset: const Offset(
13.0, 35.0), // shadow direction: bottom right
)
]),
child: Image.asset(
"assets/images/image_${number.toInt() + 1}.jpg",
fit: BoxFit.fill),
),
),
),
],
);
}
}
And this is the image that I'm expecting right now.
Yeah, I solved it with wrapping the Padding of both text and the ListView with Transform.translate and did some tinkering with the offset.
Thank God I solved this! :)
Try to place a column inside the singlechildscrollview and define mainaxisalignment as min
Set height property of Container widget wrapping PageView.

How to create responsive screen for every device in flutter?

I have a screen as attached. Stack position is not responsive for low resolution device. So how can I create this screen to fix in any device?
home_Screen.dart
// ignore_for_file: prefer_const_constructors_in_immutables
import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';
import 'package:thitsarparami/ui/home/components/menu.dart';
import '../../helper/constants.dart';
import '../../helper/enum.dart';
import '../chanting/chanting_catalog_screen.dart';
import '../monk/monk_screen.dart';
import '../radio/radio_screen.dart';
import '../youtube/video_screen.dart';
import 'components/monk_carousel.dart';
import 'components/myanmar_calender.dart';
class HomeScreen extends StatefulWidget {
static const routeName = '/home';
final BuildContext? menuScreenContext;
final Function? onScreenHideButtonPressed;
final bool hideStatus;
const HomeScreen(
{Key? key,
this.menuScreenContext,
this.onScreenHideButtonPressed,
this.hideStatus = false})
: super(key: key);
#override
HomeState createState() => HomeState();
}
class HomeState extends State<HomeScreen> {
final _itemsView = GlobalKey();
double _stackHeight = 0;
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
RenderBox stackRB =
_itemsView.currentContext?.findRenderObject() as RenderBox;
setState(() {
_stackHeight = stackRB.size.height;
});
});
}
#override
Widget build(BuildContext context) {
final double screenHeight = MediaQuery.of(context).size.height;
final double screenWidth = MediaQuery.of(context).size.width;
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
body: SingleChildScrollView(
child: Stack(
children: [
Positioned(
top: 0,
left: 0,
right: 0,
height: screenHeight * 0.7,
child: Container(
padding: const EdgeInsets.only(
top: 30, left: 0, right: 0, bottom: 10),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Theme.of(context).primaryColorDark,
Theme.of(context).primaryColor,
Theme.of(context).primaryColorLight,
],
stops: const [
0.0,
0.5,
0.7,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Expanded(
child: Container(
width: screenWidth * 0.70,
//height: screenHeight * 0.20,
//color: Colors.black,
padding: const EdgeInsets.only(
top: 10, left: 10, right: 0, bottom: 0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
kHomeTitle1,
style: Theme.of(context).textTheme.headline1,
),
Text(
kHomeTitle2,
style: Theme.of(context).textTheme.headline2,
),
Text(
kHomeTitle3,
style: Theme.of(context).textTheme.headline3,
),
],
),
),
),
Container(
width: screenWidth * 0.30,
height: screenHeight * 0.15,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/buddha.png"),
fit: BoxFit.contain),
),
),
],
),
Container(
height: screenHeight * 0.15,
padding: const EdgeInsets.only(
top: 0, left: 20, right: 20, bottom: 10),
child: const MyanmarCalender(),
),
],
),
),
),
Positioned(
left: 0,
right: 0,
top: screenHeight * 0.30,
key: _itemsView,
child: Container(
decoration: BoxDecoration(
color: Theme.of(context).backgroundColor,
borderRadius: const BorderRadius.only(
topRight: Radius.circular(70),
),
),
child: Column(
children: [
const SizedBox(
height: 10,
),
Row(
children: [
MenuButton(
screenWidth: screenWidth,
iconData: Icons.music_video,
screen: const MonkScreen(
title: kMenuMp3,
screenMode: MonkScreenMode.song,
albumType: AlbumType.dhamatalk,
),
title: kMenuMp3,
),
MenuButton(
screenWidth: screenWidth,
iconData: Icons.play_lesson_rounded,
screen: const MonkScreen(
title: kMenuLecture,
screenMode: MonkScreenMode.lecture,
albumType: AlbumType.lecture,
),
title: kMenuLecture,
),
],
),
Row(
children: [
MenuButtonWithImageIcon(
screenWidth: screenWidth,
assetImage:
const AssetImage('assets/images/book.jpeg'),
screen: const MonkScreen(
title: kMenuEbook,
screenMode: MonkScreenMode.book,
albumType: AlbumType.ebook,
),
title: kMenuEbook,
),
MenuButtonWithImageIcon(
screenWidth: screenWidth,
assetImage:
const AssetImage('assets/images/prayer.png'),
screen: const ChantingCatalogScreen(),
title: kMenuChantig,
),
],
),
Row(
children: [
MenuButton(
screenWidth: screenWidth,
iconData: Icons.video_camera_front_outlined,
screen: const VideoScreen(),
title: kLiveStreaming,
withNavBar: false,
),
MenuButton(
screenWidth: screenWidth,
iconData: Icons.radio,
screen: const RadioScreen(),
title: kOnlineRadio,
),
],
),
const SizedBox(
height: 10,
),
const AutoSizeText(
kLatestDhama,
style: TextStyle(
fontSize: 18,
),
),
const SizedBox(
height: 10,
),
const MonkCarousel(),
],
),
),
),
Container(
height: _stackHeight + (screenHeight * 0.45),
),
],
),
),
);
}
}
iPhone 13 pro max vs iPhone 8
You can use the mediaQuery class which is a built-in component in Flutter to get the user's specifications - height and width etc - and then define some terms to suit their design size
for example:
Container(
width: mediaQuery.of(context).size.width * 0.5,
height: 150,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/buddha.png"),
fit: BoxFit.contain),
In this example we told the container width to take 50% of the screen width on any devise, you can use it wherever you want. you can read more about it in the official docs: https://api.flutter.dev/flutter/widgets/MediaQuery-class.html
You can create static class for size
class AppSize{
static double width=MediaQuery.of(context).size.width;
static double height=MediaQuery.of(context).size.height;
}
if you want use like that
Container(
width: AppSize.width * 0.1 ,
height: AppSize.height * 0.6 ,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/buddha.png"),
fit: BoxFit.contain),

Transparent card but with shadow effect from elevation

I'm having trouble making a card that has a transparent white color (opacity 0.4). But, with shadow from the elevation effect.
If I remove the elevation, there's no shadow effect and the card look transparent. But, if I add some elevation, the transparent effect ruined. Here's what I've tried:
Widget cardMenu(String title) {
return Container(
padding: EdgeInsets.symmetric(horizontal: UIComponent.componentPadding),
child: Stack(
alignment: Alignment.topCenter,
children: [
Positioned(
top: -100,
child: Container(
child: Container(
height: 200,
width: 200,
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
child: Center(
child: Text(
title,
style: TextStyle(color: Colors.transparent),
),
),
),
)
),
Align(
alignment: Alignment.bottomCenter,
child: Card(
elevation: 0,
color: Colors.white.withOpacity(0.4),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(UIComponent.cardButtonRadius),
),
),
child: Container(
height: 350,
width: 180,
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Container(
padding: EdgeInsets.all(UIComponent.widgetPadding),
child: Text(
title,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: UIComponent.h1,
color: UIComponent.neutralDark,
),
),
)
],
),
),
),
)
],
),
);
}
The output of my code:
What I'm expecting to be:
Hii Christophorus Anindityo N
Make a class for BoxShadow property of container.
class CustomBoxShadow extends BoxShadow {
final BlurStyle blurStyle;
const CustomBoxShadow({
Color color = const Color(0xFF000000),
Offset offset = Offset.zero,
double blurRadius = 0.0,
this.blurStyle = BlurStyle.normal,
}) : super(color: color, offset: offset, blurRadius: blurRadius);
#override
Paint toPaint() {
final Paint result = Paint()
..color = color
..maskFilter = MaskFilter.blur(this.blurStyle, blurSigma);
assert(() {
if (debugDisableShadows)
result.maskFilter = null;
return true;
}());
return result;
}
}
And use this class in a Container
Container(
child: Center(
child: Container(
height: 200.0,
width: 300.0
decoration: BoxDecoration(
boxShadow: [
CustomBoxShadow(
color: Colors.black,
offset: Offset(5.0, 5.0),
blurRadius: 5.0,
blurStyle: BlurStyle.outer
)
],
),
child: Text("Transparent Card with Shadow", style:TextStyle(fontSize:15))),
)
)
Now you are good to code :)

How to clip one container over another in flutter?

I want to build a reusable card widget, it will have an image and text with some custom design layout. I tried everything I could, but wasn't able to achieve the desired result. Any help would be much appreciated.
This is what I want to do
I'm stuck here
This is my code
class ReusabelCard extends StatelessWidget {
ReusabelCard(
{this.cardChild, #required this.assetImagePath, #required this.cardText});
final Widget cardChild;
final String assetImagePath;
final String cardText;
#override
Widget build(BuildContext context) {
return Container(
height: MediaQuery.of(context).size.height * 0.35,
width: MediaQuery.of(context).size.width * 0.5,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(MediaQuery.of(context).size.width * 0.5 * 0.28),
),
child: Stack(
children: [
LayoutBuilder(
builder: (context, contraint) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Icon(
Icons.trip_origin,
size: contraint.biggest.width,
color: Colors.grey[300],
),
Container(
height: MediaQuery.of(context).size.height*0.05,
width: MediaQuery.of(context).size.width,
color: Colors.green,
),
],
);
},
),
],
)
);
}
}
Use ClipRRect to do it:
ClipRRect(
borderRadius: BorderRadius.circular(50.0), //clipping the whole widget
child: Container(
height: MediaQuery.of(context).size.height * 0.4, //I adjusted here for responsiveness problems on my device
width: MediaQuery.of(context).size.width * 0.5,
color: Colors.white,
child: LayoutBuilder(
builder: (context, constraint) {
return Stack(
children: [
Center(
child: Icon(
Icons.trip_origin,
size: constraint.biggest.width,
color: Colors.grey[300],
),
),
Positioned(
right: 0,
left: 0,
top: 20.0,
child: Icon(
Icons.sports_volleyball_rounded, //just to represent the ball
size: constraint.biggest.width * 0.5,
),
),
Positioned(
bottom: 0.0,
child: Container(
alignment: Alignment.center,
height: MediaQuery.of(context).size.height * 0.1,
width: constraint.biggest.width,
color: Colors.yellow[700],
child: Text(
'Sports',
style: Theme.of(context)
.textTheme
.headline3
.copyWith(color: Colors.white),
),
),
),
],
);
},
),
),
);