How to create a border like this in Flutter? - flutter

How to create a border like this:

You can achieve a similar clipped border using CustomClipper. Here is a simple CustomClipper I have created for you.
First Create a custom clipper.
class MyClipper extends CustomClipper<Path> {
#override
Path getClip(Size size) {
var smallLineLength = size.width / 20;
const smallLineHeight = 20;
var path = Path();
path.lineTo(0, size.height);
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
path.lineTo(smallLineLength * i, size.height);
} else {
path.lineTo(smallLineLength * i, size.height - smallLineHeight);
}
}
path.lineTo(size.width, 0);
path.close();
return path;
}
#override
bool shouldReclip(CustomClipper old) => false;
}
And wrap the created CustomClipper with ClipPath.
SizedBox(
height: 200,
width: 500,
child: ClipPath(
clipper: MyClipper(),
child: Container(
height: 200,
width: 500,
alignment: Alignment.center,
color: Colors.red,
child: const Text("abc"),
)),
),
Full Code:
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: MyWidget(),
),
);
}
}
class MyWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Center(
child: Column(crossAxisAlignment: CrossAxisAlignment.center, children: [
SizedBox(
height: 200,
width: 500,
child: ClipPath(
clipper: MyClipper(),
child: Container(
height: 200,
width: 500,
alignment: Alignment.center,
color: Colors.red,
child: const Text("abc"),
)),
),
]),
);
}
}
class MyClipper extends CustomClipper<Path> {
#override
Path getClip(Size size) {
var smallLineLength = size.width / 20;
const smallLineHeight = 20;
var path = Path();
path.lineTo(0, size.height);
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
path.lineTo(smallLineLength * i, size.height);
} else {
path.lineTo(smallLineLength * i, size.height - smallLineHeight);
}
}
path.lineTo(size.width, 0);
path.close();
return path;
}
#override
bool shouldReclip(CustomClipper old) => false;
}
You can run this code by copying/pasting in dartpad.
You can learn more about CustomClipper from here, medium article

Try below code hope its helpful to you. Used flutter_custom_clippers package here and used PointsClipper() for your expected design In this package you used more shapes see documentation in given link. add flutter_custom_clippers: ^2.0.0 dependency in your pubspec.yaml file
ClipPath(
clipper: PointsClipper(),
child: Container(
height: 100,
color: Colors.grey[300],
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
'Total',
style: TextStyle(
color: Colors.pink,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
Text(
'QAR 130.00',
style: TextStyle(
color: Colors.pink,
fontSize: 15,
fontWeight: FontWeight.bold,
),
),
],
),
),
),
),
Your result screen->

import 'package:flutter/material.dart';
import 'a.dart';
void main() => runApp(VideoPlayerApp());
class VideoPlayerApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Zigzag',
home: SafeArea(
child: Scaffold(
body: ZigzagApp(),
),
),
);
}
}
class ZigzagApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
height: 200,
color: Colors.pinkAccent,
child: CustomPaint(
size: MediaQuery.of(context).size,
painter: MyPainter(),
),
);
}
}
//paint widget for zigzag
import 'package:flutter/material.dart';
import 'dart:math' as math;
class MyPainter extends CustomPainter {
#override
void paint(Canvas canvas, Size size) {
var paint = Paint();
paint.color = Colors.white;
paint.style = PaintingStyle.fill;
paintZigZag(canvas, paint, Offset(0, 200), Offset(400, 200), 35, 10);
}
void paintZigZag(Canvas canvas, Paint paint, Offset start, Offset end,
int zigs, double width) {
assert(zigs.isFinite);
assert(zigs > 0);
canvas.save();
canvas.translate(start.dx, start.dy);
end = end - start;
canvas.rotate(math.atan2(end.dy, end.dx));
final double length = end.distance;
final double spacing = length / (zigs * 2.0);
final Path path = Path()..moveTo(0.0, 0.0);
for (int index = 0; index < zigs; index += 1) {
final double x = (index * 2.0 + 1.0) * spacing;
final double y = width * ((index % 2.0) * 2.0 - 1.0);
path.lineTo(x, y);
}
path.lineTo(length, 0.0);
canvas.drawPath(path, paint);
canvas.restore();
}
#override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}

Related

Can't solve this "The method 'WaveBasePainter' isn't defined for the type '_PlayerAppState'" error

I'm following this speed code tutorial (https://www.youtube.com/watch?v=KO_PYJKHglo) and currently facing some problems. Where it all started is somewhere at 2:42 in the youtube video.
This is my main.dart file.
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
debugShowCheckedModeBanner: false,
home: PlayerApp(),
),
);
}
class PlayerApp extends StatefulWidget {
const PlayerApp({super.key});
#override
State<PlayerApp> createState() => _PlayerAppState();
}
class _PlayerAppState extends State<PlayerApp> {
#override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
return Scaffold(
body: Stack(
children: <Widget>[
Positioned(
height: height,
width: width,
child: Material(
elevation: 16,
color: const Color(0xFFd6dde5), //Background Color
borderRadius: BorderRadius.circular(20),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 30.0,
),
child: Column(
children: <Widget>[
const SizedBox(
height: 90,
),
const Text(
'Music title',
),
const SizedBox(
height: 15,
),
const Text(
'Music artist',
),
const SizedBox(
height: 75,
),
buildRecordPlayer(),
const SizedBox(
height: 60,
),
Row(
children: <Widget>[
const Text('time'),
const SizedBox(
width: 8,
),
buildWave(),
const SizedBox(
width: 8,
),
const Text('end'),
],
)
],
),
),
),
)
],
),
);
}
Widget buildRecordPlayer() {
return Container(
height: 190,
width: 190,
alignment: Alignment.center,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/vinyl.png'),
fit: BoxFit.fitHeight,
colorFilter: ColorFilter.mode(
Colors.blue,
BlendMode.color,
),
),
shape: BoxShape.circle,
),
child: ClipOval(
child: Image.asset(
'assets/images/SL.png',
height: 150,
width: 150,
fit: BoxFit.fill,
),
),
);
}
Widget buildWave() {
return SizedBox(
width: 260,
height: 40,
child: CustomPaint(
painter: WaveBasePainter(),
),
);
}
}
And this is my wave_base_painter.dart file
import 'package:flutter/material.dart';
import 'dart:math';
class WaveBasePainter extends CustomPainter {
Paint? _paint; //4:03
#override
void paint(Canvas canvas, Size size) {
_paint = Paint()
..color = Colors.grey.withOpacity(0.3)
..style = PaintingStyle.stroke
..strokeWidth = 1.5;
canvas.translate(0, size.height / 2);
canvas.scale(1, -1);
for (int i = 0; i < size.width.toInt(); i++) {
double x = i.toDouble();
double r = 2 * sin(i) - 2 * cos(4 * i) + sin(2 * i - pi * 24);
r = r * 5;
canvas.drawLine(Offset(x, r), Offset(x, -r), _paint!);
}
#override
bool shouldRepaint(WaveBasePainter oldDelegate) => false;
}
}
This is what it resulted and I have no idea why the speed code video that I'm following doesn't show any errors and mine does.
You have defined shouldRepaint function incorrectly.
You can see this file, I have updated it:
class WaveBasePainter extends CustomPainter {
Paint? _paint; //4:03
#override
void paint(Canvas canvas, Size size) {
_paint = Paint()
..color = Colors.grey.withOpacity(0.3)
..style = PaintingStyle.stroke
..strokeWidth = 1.5;
canvas.translate(0, size.height / 2);
canvas.scale(1, -1);
for (int i = 0; i < size.width.toInt(); i++) {
double x = i.toDouble();
double r = 2 * sin(i) - 2 * cos(4 * i) + sin(2 * i - pi * 24);
r = r * 5;
canvas.drawLine(Offset(x, r), Offset(x, -r), _paint!);
}
}
#override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return false;
}
}

How to make a cutout in a container using ClipPath?

I have a page on which the container is located, I need to make borders and a cutout for the buttons in this container. I want to do this using ClipPath when I added this widget, nothing has changed, there are no borders and there is no vyzer that I registered. Tell me why nothing is displayed, what is my mistake?
#override
Widget build(BuildContext context) {
return ClipPath(
clipper: CustomClipperArc(position: 150, holeRadius: 32),
child: Container(
decoration: const BoxDecoration(
color: constants.Colors.greyXDark,
),
padding: const EdgeInsets.only(top: 50),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SvgPicture.asset(
constants.Assets.likeBoarding,
height: 50,
),
],
),
],
),
),
);
}
CustomClipperArc
class CustomClipperArc extends CustomClipper<Path> {
CustomClipperArc({this.position, this.holeRadius = 16});
double? position;
final double holeRadius;
#override
Path getClip(Size size) {
final path = Path()
..moveTo(0, 0)
..lineTo(position! - holeRadius, 0.0)
..lineTo(size.width, 0.0)
..lineTo(size.width, size.height)
..lineTo(position!, size.height)
..arcToPoint(
Offset(position! - holeRadius, size.height),
clockwise: false,
radius: const Radius.circular(1),
);
path.lineTo(0.0, size.height);
path.close();
return path;
}
#override
bool shouldReclip(CustomClipper oldClipper) => oldClipper != this;
}
Here is your Clip Code... and also use Shape Maker to design such layout and you will get clip code
Your clip container with border
Padding(
padding: const EdgeInsets.all(8.0),
child: Stack(
children: <Widget>[
ClipPath(
clipper: CustomClipPathTopContainer(),
child: Container(
height: 400,
color: Colors.green,
),
),
CustomPaint(
painter: BorderPainter(),
child: Container(
height: 400,
),
),
],
),
),
Clipping Code of Container
import 'package:flutter/cupertino.dart';
class CustomClipPathTopContainer extends CustomClipper<Path> {
#override
Path getClip(Size size) {
double w = size.width;
double h = size.height;
Path path0 = Path();
path0.moveTo(0,size.height);
path0.lineTo(0,0);
path0.lineTo(size.width,0);
path0.lineTo(size.width,size.height);
path0.lineTo(size.width*0.3333333,size.height);
path0.lineTo(size.width*0.3014833,size.height*0.9182714);
path0.quadraticBezierTo(size.width*0.2795000,size.height*0.8617714,size.width*0.2488333,size.height*0.8552714);
path0.quadraticBezierTo(size.width*0.2145667,size.height*0.8643571,size.width*0.1948583,size.height*0.9179714);
path0.lineTo(size.width*0.1653417,size.height);
path0.lineTo(0,size.height);
path0.lineTo(0,size.height);
path0.lineTo(0,size.height);
path0.close();
return path0;
}
#override
bool shouldReclip(CustomClipper<Path> oldClipper) => false;
}
Making Border Painting
class BorderPainter extends CustomPainter {
#override
void paint(Canvas canvas, Size size) {
Paint paint = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 2
..color = Colors.pink;
Path path0 = Path();
path0.moveTo(0,size.height);
path0.lineTo(0,size.height*0.2114714);
path0.quadraticBezierTo(size.width*0.1255833,size.height*0.4277857,size.width*0.2698833,size.height*0.4275143);
path0.cubicTo(size.width*0.4168083,size.height*0.4270286,size.width*0.5467250,size.height*0.0190429,size.width*0.6867167,size.height*0.0189000);
path0.quadraticBezierTo(size.width*0.8293000,size.height*0.0211000,size.width,size.height*0.2121429);
path0.lineTo(size.width,size.height);
path0.lineTo(0,size.height);
path0.lineTo(0,size.height);
path0.lineTo(0,size.height*0.9994143);
path0.close();
canvas.drawPath(path0, paint);
}
#override
bool shouldRepaint(CustomPainter oldDelegate) => true;
}

How to add arrow at bottom of a message box in flutter?

Please help me on how can I create this box
message box to be created in flutter
you ca use these packages to have a bubble shape for a message
bubble: ^1.2.1
flutter_chat_bubble: ^2.0.0
You can use the bubble from material design by importing
import 'package:flutter/material.dart';
or simply :-
Bubble(
margin: BubbleEdges.only(leftBottom: 10),
nip: BubbleNip.rightTop,
color: Color.fromRGBO(225, 255, 199, 1.0),
child: Text('Your Text', textAlign: TextAlign.right)
If u need more reference read this.
you can use customPainter or CustomClipper , in this case, better use clipper because we need all size from its child,
code :
import 'package:flutter/material.dart';
class MessageBox extends StatefulWidget {
const MessageBox({Key? key}) : super(key: key);
#override
_MessageBoxState createState() => _MessageBoxState();
}
class _MessageBoxState extends State<MessageBox> {
#override
Widget build(BuildContext context) {
return Material(
child: Column(
children: [
const SizedBox(height: 200,),
Container(
width: MediaQuery.of(context).size.width,
height: 100,
decoration: BoxDecoration(
color: Colors.purple,
borderRadius: BorderRadius.circular(35.0)
),
),
ClipPath(
clipper: MessageClipper(),
child: Container(
height: 20,
width: MediaQuery.of(context).size.width,
color: Colors.purple,
),
)
],
),
);
}
}
class MessageClipper extends CustomClipper<Path> {
#override
Path getClip(Size size) {
var firstOffset = Offset(size.width * 0.1, 0.0);
var secondPoint = Offset(size.width * 0.15, size.height );
var lastPoint = Offset(size.width * 0.2, 0.0);
var path = Path()
..moveTo(firstOffset.dx, firstOffset.dy)
..lineTo(secondPoint.dx, secondPoint.dy)
..lineTo(lastPoint.dx, lastPoint.dy)
..close();
return path;
}
#override
bool shouldReclip(covariant CustomClipper<Path> oldClipper) {
return true;
}
}
here result :

Flutter _debugLifecycleState != _ElementLifecycle.defunct': is not true

I am showing some animated custom painter progress bar in my app it's showing some error
Error: The following assertion was thrown while notifying listeners for AnimationController:
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4263 pos 12: '_debugLifecycleState != _ElementLifecycle.defunct': is not true.
I have a simple homePage in which I have a navigation bar. I am simply showing the container when navigation change like this
SingleChildScrollView(
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("images/sidebg.png"),
fit: BoxFit.cover,
),
),
child: Column(
children: [
pageIndex == 0 ? DashboardScreen() : Container(),
pageIndex == 1 ? MapScreen() : Container(),
pageIndex == 3 ? ServiceCenter() : Container(),
pageIndex == 4 ? ProfileScreen() : Container(),
],
)),
),
Issue is as you can see pages changes when index are changing but when i change the page its showing an error as i mention above in continuesly loop not stopping.
If I remove this progress indicator all is working fine.
This is the progress indicator screen
import 'dart:math' as math;
import 'package:curved_navigation_bar/curved_navigation_bar.dart';
import 'package:sleek_circular_slider/sleek_circular_slider.dart';
import 'package:liquid_progress_indicator/liquid_progress_indicator.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:smooth_star_rating/smooth_star_rating.dart';
class DashboardScreen extends StatefulWidget {
#override
_DashboardScreenState createState() => _DashboardScreenState();
}
class _DashboardScreenState extends State<DashboardScreen> {
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Container(
child: Column(
children: [
SizedBox(
height: height * 0.05,
),
Circular_arc(),
],
),
);
}
}
final Gradient gradient = new LinearGradient(
colors: <Color>[
Colors.greenAccent.withOpacity(1.0),
Colors.yellowAccent.withOpacity(1.0),
Colors.redAccent.withOpacity(1.0),
],
stops: [
0.0,
0.5,
1.0,
],
);
class Circular_arc extends StatefulWidget {
const Circular_arc({
Key key,
}) : super(key: key);
#override
_Circular_arcState createState() => _Circular_arcState();
}
class _Circular_arcState extends State<Circular_arc>
with SingleTickerProviderStateMixin {
Animation<double> animation;
AnimationController animController;
#override
void initState() {
// TODO: implement initState
super.initState();
animController =
AnimationController(duration: Duration(seconds: 3), vsync: this);
final curvedAnimation =
CurvedAnimation(parent: animController, curve: Curves.easeInOutCubic);
animation = Tween<double>(begin: 0.0, end: 2).animate(curvedAnimation)
..addListener(() {
setState(() {});
});
animController.repeat(max: 1);
}
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Container(
child: Stack(
children: [
CustomPaint(
size: Size(300, 300),
painter: ProgressArc(null, Colors.black54, true),
),
CustomPaint(
size: Size(300, 300),
painter: ProgressArc(animation.value, Colors.redAccent, false),
),
Positioned(
top: height * 0.07,
left: width * 0.2,
child: Column(
children: [
Image.asset(
'images/star-icon-fill#3x.png',
height: height * 0.045,
),
RichText(
text: new TextSpan(
// Note: Styles for TextSpans must be explicitly defined.
// Child text spans will inherit styles from parent
style: new TextStyle(
fontSize: 14.0,
color: Colors.black,
),
children: <TextSpan>[
new TextSpan(
text: '4.6',
style: new TextStyle(
fontSize: 40, fontFamily: 'UbuntuRegular')),
new TextSpan(
text: ' /5',
style: TextStyle(
fontSize: 25,
color: Colors.grey[400],
fontFamily: 'UbuntuRegular')),
],
),
),
Text(
'FIFTEEN DAYS SCORE',
style: TextStyle(
color: Colors.grey[400], fontFamily: 'UbuntuMedium'),
)
],
),
)
],
),
);
}
}
class ProgressArc extends CustomPainter {
bool isBackground;
double arc;
Color progressColor;
ProgressArc(this.arc, this.progressColor, this.isBackground);
#override
void paint(Canvas canvas, Size size) {
final rect = Rect.fromLTRB(0, 0, 300, 300);
final startAngle = -math.pi;
final sweepAngle = arc != null ? arc : math.pi;
final userCenter = false;
final paint = Paint()
..strokeCap = StrokeCap.round
..color = progressColor
..style = PaintingStyle.stroke
..strokeWidth = 10;
if (!isBackground) {
paint.shader = gradient.createShader(rect);
}
canvas.drawArc(rect, startAngle, sweepAngle, userCenter, paint);
}
#override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
// TODO: implement shouldRepaint
return true;
}
}
Error is in the continuous loop it's not stopping. And also its starts when I change the page index (mean when I change the navigation from home).
In your _CircularArcState, please...
Call animController.forward(); after animController.repeat(max: 1);
To save the state of CircularArc, add mixin AutomaticKeepAliveClientMixin in _CircularArcState. Then override wantKeepAlive and return true. Also, call super.build(context); inside build(...).
import 'dart:math' as math;
import 'dart:ui';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: PageView(
scrollDirection: Axis.vertical,
children: [
DashboardScreen(),
Container(color: Colors.orange),
Container(color: Colors.blue),
Container(color: Colors.green),
],
),
),
);
}
}
class DashboardScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Container(
child: Column(
children: [
SizedBox(
height: height * 0.05,
),
CircularArc(),
],
),
);
}
}
final Gradient gradient = new LinearGradient(
colors: <Color>[
Colors.greenAccent.withOpacity(1.0),
Colors.yellowAccent.withOpacity(1.0),
Colors.redAccent.withOpacity(1.0),
],
stops: [0.0, 0.5, 1.0],
);
class CircularArc extends StatefulWidget {
const CircularArc({
Key key,
}) : super(key: key);
#override
_CircularArcState createState() => _CircularArcState();
}
class _CircularArcState extends State<CircularArc>
with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
double width;
double height;
Animation<double> animation;
#override
void initState() {
super.initState();
final AnimationController animController =
AnimationController(duration: Duration(seconds: 3), vsync: this);
final curvedAnimation =
CurvedAnimation(parent: animController, curve: Curves.easeInOutCubic);
animation = Tween<double>(begin: 0.0, end: 2).animate(curvedAnimation)
..addListener(() {
setState(() {});
});
animController.repeat(max: 1);
animController.forward();
}
#override
bool get wantKeepAlive => true;
#override
Widget build(BuildContext context) {
super.build(context);
if (width == null && height == null) {
width = MediaQuery.of(context).size.width;
height = MediaQuery.of(context).size.height;
}
return Container(
child: Stack(
children: [
CustomPaint(
size: Size(300, 300),
painter: ProgressArc(null, Colors.black54, true),
),
CustomPaint(
size: Size(300, 300),
painter: ProgressArc(animation.value, Colors.redAccent, false),
),
Positioned(
top: height * 0.07,
left: width * 0.2,
child: Column(
children: [
// Image.asset(
// 'images/star-icon-fill#3x.png',
// height: height * 0.045,
// ),
RichText(
text: new TextSpan(
// Note: Styles for TextSpans must be explicitly defined.
// Child text spans will inherit styles from parent
style: new TextStyle(
fontSize: 14.0,
color: Colors.black,
),
children: <TextSpan>[
new TextSpan(
text: '4.6',
style: new TextStyle(
fontSize: 40, fontFamily: 'UbuntuRegular')),
new TextSpan(
text: ' /5',
style: TextStyle(
fontSize: 25,
color: Colors.grey[400],
fontFamily: 'UbuntuRegular')),
],
),
),
Text(
'FIFTEEN DAYS SCORE',
style: TextStyle(
color: Colors.grey[400], fontFamily: 'UbuntuMedium'),
)
],
),
)
],
),
);
}
}
class ProgressArc extends CustomPainter {
bool isBackground;
double arc;
Color progressColor;
ProgressArc(this.arc, this.progressColor, this.isBackground);
#override
void paint(Canvas canvas, Size size) {
final rect = Rect.fromLTRB(0, 0, 300, 300);
final startAngle = -math.pi;
final sweepAngle = arc != null ? arc : math.pi;
final userCenter = false;
final paint = Paint()
..strokeCap = StrokeCap.round
..color = progressColor
..style = PaintingStyle.stroke
..strokeWidth = 10;
if (!isBackground) {
paint.shader = gradient.createShader(rect);
}
canvas.drawArc(rect, startAngle, sweepAngle, userCenter, paint);
}
#override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
// TODO: implement shouldRepaint
return true;
}
}
first dispose the controller and then use super.dispose()
void dispose() { controller.dispose(); super.dispose(); }

Draw Bezier curve with rectangle in Flutter

I'm starting with Flutter and have to design a UI that looks like
But with icon button at the center of the Bezier curve.
What I tried is
class HeaderPainter extends CustomPainter {
HeaderPainter({
#required this.color,
#required this.avatarRadius
});
final Color color;
final double avatarRadius;
#override
void paint(Canvas canvas, Size size) {
final shapeBounds = Rect.fromLTRB(0, 0, size.width, size.height - avatarRadius);
final centerAvatar = Offset(shapeBounds.center.dx, shapeBounds.bottom);
final avatarBounds = Rect.fromCircle(center: centerAvatar, radius: avatarRadius).inflate(3);
_drawBackground(canvas, shapeBounds, avatarBounds);
}
#override
bool shouldRepaint(HeaderPainter oldDelegate) {
return color != oldDelegate.color;
}
void _drawBackground(Canvas canvas, Rect shapeBounds, Rect avatarBounds) {
final paint = Paint()..color = color;
final backgroundPath = Path()
..moveTo(shapeBounds.left, shapeBounds.top)
..lineTo(shapeBounds.bottomLeft.dx, shapeBounds.bottomLeft.dy)
..arcTo(avatarBounds, -pi, pi, false)
..lineTo(shapeBounds.bottomRight.dx, shapeBounds.bottomRight.dy)
..lineTo(shapeBounds.topRight.dx, shapeBounds.topRight.dy)
..lineTo(0.0, shapeBounds.height - 100)
..quadraticBezierTo(
shapeBounds.width / 4, shapeBounds.height,
shapeBounds.width / 2, shapeBounds.height
)
..quadraticBezierTo(
shapeBounds.width - shapeBounds.width / 4, shapeBounds.height,
shapeBounds.width, shapeBounds.height - 100
)
..lineTo(shapeBounds.width, 0.0)
..close();
canvas.drawPath(backgroundPath, paint);
}
}
And the outcome is
How can I get the bezier curve with the rectangle?
Edit 2: The HeaderPainter is used like
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Container(
child: CustomPaint(
size: Size.fromHeight(400.0),
painter: HeaderPainter(
color: Colors.red,
avatarRadius: avatarRadius
),
),
),
Positioned(
left: 0,
right: 0,
bottom: titleBottomMargin,
child: Column(
children: <Widget>[
Text('Hello World', style: TextStyle(fontWeight: FontWeight.bold),),
],
),
),
Align(
alignment: Alignment.bottomCenter,
child: CircleAvatar(
radius: avatarRadius,
backgroundColor: Colors.green,
child: IconButton(icon: Icon(Icons.message), onPressed: _onAddMessageButtonClick,),
),
)
],
);
}
Got it solved using ClipPath and CustomClipper.
The updated build() method is
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Container(
child: ClipPath(
clipper: HeaderClipper(avatarRadius: avatarRadius),
child: CustomPaint(
size: Size.fromHeight(400.0),
painter: HeaderPainter(
color: Colors.green,
avatarRadius: avatarRadius
),
),
),
),
...
and HeaderClipper
class HeaderClipper extends CustomClipper<Path> {
HeaderClipper({
#required this.avatarRadius
});
final avatarRadius;
#override
getClip(Size size) {
final path = Path()
..lineTo(0.0, size.height - 100)
..quadraticBezierTo(
size.width / 4, (size.height - avatarRadius),
size.width / 2, (size.height - avatarRadius)
)
..quadraticBezierTo(
size.width - (size.width / 4), (size.height - avatarRadius),
size.width, size.height - 100
)
..lineTo(size.width, 0.0)
..close();
return path;
}
#override
bool shouldReclip(CustomClipper oldClipper) {
return false;
}
}
The final output is