How to clip overflow inside a BoxDecoration - dart

I want to create a widget like a CircleAvatar that clips its child when it overflows (CircleAvatar only clip the image, not its child). Can I force a BoxDecoration to clip its child (like overflow: hidden in css)?
Consider I have these:
new Container(
height: 50.0,
alignment: Alignment.bottomCenter,
decoration: new BoxDecoration(
color: Colors.blue,
border: new Border.all(),
borderRadius: new BorderRadius.circular(25.0),
),
child: new Container(
color: Colors.orange,
height: 20.0,
),
)
I want orange box to be contained in blue circle.

There is a ClipOval class that can be used like this:
class ClipExample extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.blueAccent,
body: new Center(
child: new CircleAvatar(
backgroundColor: Colors.amberAccent,
child: new ClipOval(
clipper:new MyClipper(),
child: new Container(
color: Colors.red,
height: 10.0,
),
),
),
),
);
}
}
class MyClipper extends CustomClipper<Rect>{
#override
Rect getClip(Size size) {
return new Rect.fromCircle(center: new Offset(0.0,0.0),
radius: 50.0
);
}
#override
bool shouldReclip(CustomClipper<Rect> oldClipper) {
return false;
}
}

Related

How to create a button with rounded corner, and gradient background?

I have been trying to create a raised button with a rounded corner, and gradient background but to no success. I can only implement one or the other. It's been 2 hours and I haven't found a solution myself, on how I can implement both a rounded corner, and a gradient background together.
Below are my codes of my latest attempt to implement a raised button with rounded corner, and gradient background.
Custom class of GradientButton
class RaisedGradientButton extends StatelessWidget {
final Widget child;
final Gradient gradient;
final double width;
final double height;
final Function onPressed;
const RaisedGradientButton({
Key key,
#required this.child,
this.gradient,
this.width = double.infinity,
this.height = 50.0,
this.onPressed,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
width: width,
height: 50.0,
decoration: BoxDecoration(
gradient: new LinearGradient(
colors: [
Colors.blue,
Colors.red,
],
begin: FractionalOffset.centerLeft,
end: FractionalOffset.centerRight,
),
),
child: Material(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(128.0)),
// color: Colors.transparent,
child: InkWell(
onTap: onPressed,
child: Center(
child: child,
)),
),
);
}
}
How I use the above code:
RaisedGradientButton(
onPressed: navigateToNextPage,
child: Text("Select Community"),
)
How it looks like:
As you can see, the gradient is there, but when I attempt to create a rounded corner, it overlaps, and the gradient is behind.
There is a simple solution. Add the same border radius to both the button and the container inside the button. Here is a simple example.
RaisedButton(
onPressed: () {},
textColor: Colors.white,
color: Colors.transparent,
padding: EdgeInsets.all(0),
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(18.0),
),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(18),
gradient: LinearGradient(
colors: <Color>[
Colors.black38,
Colors.black26,
Colors.white38,
],
),
),
padding: const EdgeInsets.fromLTRB(24, 12, 24, 12),
child: const Text('Sign In', style: TextStyle(fontSize: 20)),
),
),
I suggest you put a Container with a gradient below the button in a Stack and cut its corners with ClipRRect while leaving the button's color transparent. This way you keep touch feedback and pressed button shadow, as well as accessibility support.
class RaisedGradientButton extends StatelessWidget {
final Widget child;
final Gradient gradient;
final double width;
final double height;
final Function onPressed;
final borderRadius = BorderRadius.circular(128.0);
RaisedGradientButton({
Key key,
#required this.child,
Gradient gradient,
this.width = double.infinity,
this.height = 50.0,
this.onPressed,
}) : this.gradient = gradient ??
LinearGradient(
colors: [
Colors.blue,
Colors.red,
],
begin: FractionalOffset.centerLeft,
end: FractionalOffset.centerRight,
),
super(key: key);
#override
Widget build(BuildContext context) => Stack(
children: [
Positioned.fill(
child: ClipRRect(
borderRadius: borderRadius,
child: Container(
width: width,
height: height,
decoration: BoxDecoration(
gradient: gradient,
),
),
),
),
Container(
width: width,
height: height,
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: borderRadius,
),
padding: EdgeInsets.zero,
child: Center(child: child),
onPressed: onPressed,
color: Colors.transparent,
),
),
],
);
}
If anyone ever encounters the same issue. Here is my code on how I got it solved.
class GradientButton extends StatelessWidget {
final Widget child;
// final Gradient gradient;
final double width;
final double height;
final bool isEnabled;
final Function onPressed;
const GradientButton({
Key key,
#required this.child,
// this.gradient,
this.isEnabled,
this.width,
this.height,
this.onPressed,
}) : super(key: key);
#override
Widget build(BuildContext context) {
Color _statusColor;
if (isEnabled != null) {
// Show gradient color by making material widget transparent
if (isEnabled == true) {
_statusColor = Colors.transparent;
} else {
// Show grey color if isEnabled is false
_statusColor = Colors.grey;
}
} else {
// Show grey color if isEnabled is null
_statusColor = Colors.transparent;
}
return Container(
width: width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
gradient: LinearGradient(
colors: [
Color(0xFF3186E3),
Color(0xFF1D36C4),
],
begin: FractionalOffset.centerLeft,
end: FractionalOffset.centerRight,
),
),
child: Material(
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(4)),
color: _statusColor,
child: InkWell(
borderRadius: BorderRadius.circular(32),
onTap: onPressed,
child: Padding(
padding: EdgeInsets.fromLTRB(24, 16, 24, 16),
child: Center(
child: child,
),
))),
);
}
}
Use ElevatedButton (Recommended as of Flutter 2.0)
#override
Widget build(BuildContext context) {
final radius = BorderRadius.circular(20);
return Scaffold(
body: Center(
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(colors: [Colors.cyanAccent, Colors.red]),
borderRadius: radius,
),
child: ElevatedButton(
onPressed: () {},
child: Text('Elevated Button'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.transparent,
shape: RoundedRectangleBorder(borderRadius: radius),
),
),
),
),
);
}

Flutter background floating window feature

Is there any way to create a background floating window using Flutter like IMO does.
Background Floating Window: This is a window which can be dragged using fingers and it is not only limited to my app. User can have my app window showing up on different apps too. Some apps that uses it include TrueCaller, IMO, etc.
Here is the screenshot, the boy window can be dragged and when you tap home button, the app will get minimised but this boy window will still be there on the home launcher and if user navigates to some other app, this window will still persist.
Screenshot Example
the below code gives you the result you want
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Unit Converter',
home: Scaffold(
body: SafeArea(
child: Center(
child: Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.red
),
),
Container(
margin: EdgeInsets.all(20),
width: 150,
height: 200,
decoration: BoxDecoration(
color: Colors.blue
)
)
],
),
),
),
),
);
}
}
A minimal E.g of What you Want:
import 'package:flutter/material.dart';
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: App(),
),
);
}
}
class App extends StatefulWidget {
#override
AppState createState() => AppState();
}
class AppState extends State<App> {
Color caughtColor = Colors.grey;
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(color: Colors.red),
),
DragBox(Offset(0.0, 0.0), 'Box One', Colors.blueAccent),
DragBox(Offset(200.0, 0.0), 'Box Two', Colors.orange),
DragBox(Offset(300.0, 0.0), 'Box Three', Colors.lightGreen),
],
);
}
}
class DragBox extends StatefulWidget {
final Offset initPos;
final String label;
final Color itemColor;
DragBox(this.initPos, this.label, this.itemColor);
#override
DragBoxState createState() => DragBoxState();
}
class DragBoxState extends State<DragBox> {
Offset position = Offset(0.0, 0.0);
#override
void initState() {
super.initState();
position = widget.initPos;
}
#override
Widget build(BuildContext context) {
return Positioned(
left: position.dx,
top: position.dy,
child: Draggable(
data: widget.itemColor,
child: Container(
width: 100.0,
height: 100.0,
color: widget.itemColor,
child: Center(
child: Text(
widget.label,
style: TextStyle(
color: Colors.white,
decoration: TextDecoration.none,
fontSize: 20.0,
),
),
),
),
onDraggableCanceled: (velocity, offset) {
setState(() {
position = offset;
});
},
feedback: Container(
width: 120.0,
height: 120.0,
color: widget.itemColor.withOpacity(0.5),
child: Center(
child: Text(
widget.label,
style: TextStyle(
color: Colors.white,
decoration: TextDecoration.none,
fontSize: 18.0,
),
),
),
),
));
}
}
A simple way to do this would be a stack.
https://docs.flutter.io/flutter/widgets/Stack-class.html

How to invert a text in Flutter?

Can anyone post a simple example of inverting a Text placed inside a Container.
Here is the starting code.
Widget _myWidget() {
return Container(
height: 100.0,
color: Colors.orange,
child: Center(child: Text("GO", style: TextStyle(fontSize: 70.0)),),
);
}
Above code shows following output:
What I want it to look like is :
This is the code to do that
import 'dart:math';
class FlipedText extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Material(
child: Transform(
transform:Matrix4.rotationX(pi),
alignment: Alignment.center,
child: Container(
height: 100.0,
color: Colors.orange,
child: Center(child: Text("GO", style: TextStyle(fontSize: 70.0)),),
),
),
);
}
}

Flutter Circle Design

I want to make this kind of design with these white circles as a raised button.
Try This!
I have added 5 circles you can add more. And instead of RaisedButton use InkResponse.
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(home: new ExampleWidget()));
}
class ExampleWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
Widget bigCircle = new Container(
width: 300.0,
height: 300.0,
decoration: new BoxDecoration(
color: Colors.orange,
shape: BoxShape.circle,
),
);
return new Material(
color: Colors.black,
child: new Center(
child: new Stack(
children: <Widget>[
bigCircle,
new Positioned(
child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.favorite_border),
top: 10.0,
left: 130.0,
),
new Positioned(
child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.timer),
top: 120.0,
left: 10.0,
),
new Positioned(
child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.place),
top: 120.0,
right: 10.0,
),
new Positioned(
child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.local_pizza),
top: 240.0,
left: 130.0,
),
new Positioned(
child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.satellite),
top: 120.0,
left: 130.0,
),
],
),
),
);
}
}
class CircleButton extends StatelessWidget {
final GestureTapCallback onTap;
final IconData iconData;
const CircleButton({Key key, this.onTap, this.iconData}) : super(key: key);
#override
Widget build(BuildContext context) {
double size = 50.0;
return new InkResponse(
onTap: onTap,
child: new Container(
width: size,
height: size,
decoration: new BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
child: new Icon(
iconData,
color: Colors.black,
),
),
);
}
}
you can use decoration like this :
Container(
width: 60,
height: 60,
child: Icon(CustomIcons.option, size: 20,),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Color(0xFFe0f2f1)),
)
Now you have circle shape and Icon on it.
More efficient way
I recommend drawing a circle with CustomPainter. It's very easy and way more efficient than creating a bunch of widgets/masks:
/// Draws a circle if placed into a square widget.
/// https://stackoverflow.com/a/61246388/1321917
class CirclePainter extends CustomPainter {
final _paint = Paint()
..color = Colors.red
..strokeWidth = 2
// Use [PaintingStyle.fill] if you want the circle to be filled.
..style = PaintingStyle.stroke;
#override
void paint(Canvas canvas, Size size) {
canvas.drawOval(
Rect.fromLTWH(0, 0, size.width, size.height),
_paint,
);
}
#override
bool shouldRepaint(CustomPainter oldDelegate) => false;
}
Usage:
Widget _buildCircle(BuildContext context) {
return CustomPaint(
size: Size(20, 20),
painter: CirclePainter(),
);
}
I would use a https://docs.flutter.io/flutter/widgets/Stack-class.html to be able to freely position widgets.
To create circles
new BoxDecoration(
color: effectiveBackgroundColor,
image: backgroundImage != null
? new DecorationImage(image: backgroundImage, fit: BoxFit.cover)
: null,
shape: BoxShape.circle,
),
and https://docs.flutter.io/flutter/widgets/Transform/Transform.rotate.html to position the white dots.

How to show fullscreen image in flutter

Is there any way to show fullscreen image ?
var imagejadwal = new Image.network(
"https://firebasestorage.googleapis.com/v0/b/c-smp-bruder.appspot.com/o/fotojadwal.jpg?alt=media&token=b35b74df-eb40-4978-8039-2f1ff2565a57",
fit: BoxFit.cover
);
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: imagejadwal
),
);
in that code, there's space around the image :/
Your problem is that Center will make the image to get it's preferred size instead of the full size.
The correct approach would be instead to force the image to expand.
return new Scaffold(
body: new Image.network(
"https://cdn.pixabay.com/photo/2017/02/21/21/13/unicorn-2087450_1280.png",
fit: BoxFit.cover,
height: double.infinity,
width: double.infinity,
alignment: Alignment.center,
),
);
The alignment: Alignment.center is unnecessary. But since you used the Center widget, I tought it would be interesting to know how to customize it.
Here is a View you wrap around your image widget
Includes a click event which opens up a full screen view of the image
Zoom and Pan image
Null-safety
Dark/Light background for PNGs
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class ImageFullScreenWrapperWidget extends StatelessWidget {
final Image child;
final bool dark;
ImageFullScreenWrapperWidget({
required this.child,
this.dark = true,
});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
PageRouteBuilder(
opaque: false,
barrierColor: dark ? Colors.black : Colors.white,
pageBuilder: (BuildContext context, _, __) {
return FullScreenPage(
child: child,
dark: dark,
);
},
),
);
},
child: child,
);
}
}
class FullScreenPage extends StatefulWidget {
FullScreenPage({
required this.child,
required this.dark,
});
final Image child;
final bool dark;
#override
_FullScreenPageState createState() => _FullScreenPageState();
}
class _FullScreenPageState extends State<FullScreenPage> {
#override
void initState() {
var brightness = widget.dark ? Brightness.light : Brightness.dark;
var color = widget.dark ? Colors.black12 : Colors.white70;
SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.top]);
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
systemNavigationBarColor: color,
statusBarColor: color,
statusBarBrightness: brightness,
statusBarIconBrightness: brightness,
systemNavigationBarDividerColor: color,
systemNavigationBarIconBrightness: brightness,
));
super.initState();
}
#override
void dispose() {
SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
// Restore your settings here...
));
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: widget.dark ? Colors.black : Colors.white,
body: Stack(
children: [
Stack(
children: [
AnimatedPositioned(
duration: Duration(milliseconds: 333),
curve: Curves.fastOutSlowIn,
top: 0,
bottom: 0,
left: 0,
right: 0,
child: InteractiveViewer(
panEnabled: true,
minScale: 0.5,
maxScale: 4,
child: widget.child,
),
),
],
),
SafeArea(
child: Align(
alignment: Alignment.topLeft,
child: MaterialButton(
padding: const EdgeInsets.all(15),
elevation: 0,
child: Icon(
Icons.arrow_back,
color: widget.dark ? Colors.white : Colors.black,
size: 25,
),
color: widget.dark ? Colors.black12 : Colors.white70,
highlightElevation: 0,
minWidth: double.minPositive,
height: double.minPositive,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100),
),
onPressed: () => Navigator.of(context).pop(),
),
),
),
],
),
);
}
}
Example Code:
ImageFullScreenWrapperWidget(
child: Image.file(file),
dark: true,
)
This is another option:
return new DecoratedBox(
decoration: new BoxDecoration(
image: new DecorationImage(
image: new AssetImage('images/lake.jpg'),
fit: BoxFit.fill
),
),
);
For Image from asset
new Image(
image: AssetImage('images/test.jpg'),
fit: BoxFit.cover,
height: double.infinity,
width: double.infinity,
alignment: Alignment.center,
),
For some reason, the solutions given in the answers here did not work for me. The below code worked for me.
body: Container(
height: double.infinity,
width: double.infinity,
child: FittedBox(child: Image.asset('assets/thunderbackground.jpg'),
fit: BoxFit.cover),
you could try wrapping image.network in a a container with infinite dimensions which takes the available size of its parent (meaning if you drop this container in lower half of screen it will fill the lower half of screen if you put this directly as the body of scaffold it will take the full screen)
Container(
height: double.infinity,
width: double.infinity,
child: Image.network(
backgroundImage1,
fit: BoxFit.cover,
)
);
You can use MediaQuery class if you want to get the precious size of your device and use it to manage the size of your image, here's the examples:
return Container(
color: Colors.white,
child: Image.asset(
'assets/$index.jpg',
fit: BoxFit.fill,
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
alignment: Alignment.center,
),
);
Here is an example of a FadeInImage with another widget overlay using the double.infinity method as in the accepted answer.
class FullScreenImage extends StatelessWidget {
#override
Widget build(BuildContext context) {
//you do not need container here, STACK will do just fine if you'd like to
//simplify it more
return Container(
child: Stack(children: <Widget>[
//in the stack, the background is first. using fit:BoxFit.cover will cover
//the parent container. Use double.infinity for height and width
FadeInImage(
placeholder: AssetImage("assets/images/blackdot.png"),
image: AssetImage("assets/images/woods_lr_50.jpg"),
fit: BoxFit.cover,
height: double.infinity,
width: double.infinity,
//if you use a larger image, you can set where in the image you like most
//width alignment.centerRight, bottomCenter, topRight, etc...
alignment: Alignment.center,
),
_HomepageWords(context),
]),
);
}
}
//example words and image to float over background
Widget _HomepageWords(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
InkWell(
child: Padding(
padding: EdgeInsets.all(30),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(0, 40, 0, 12),
child: Image.asset(
"assets/images/Logo.png",
height: 90,
semanticLabel: "Logo",
),
),
Text(
"ORGANIZATION",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white),
),
Text(
"DEPARTMENT",
style: TextStyle(
fontSize: 50,
fontWeight: FontWeight.bold,
color: Colors.white),
),
Text(
"Disclaimer information...",
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: Colors.white),
),
],
),
),
onTap: () {
//to another screen / page or action
},
),
],
);
}
Use the below code if height: double.infinity, width: double.infinity, doesn't work to u.
class SplashScreen extends StatefulWidget {
#override
_SplashScreenState createState() => new _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
#override
void initState() {
super.initState();
Timer(Duration(seconds: 30),()=>Navigator.push(
context, MaterialPageRoute(builder: (context)=>Login())));
}
#override
Widget build(BuildContext context) {
return new Scaffold(
//backgroundColor: Colors.white,
body: Container(
child: new Column(children: <Widget>[
new Image.asset(
'assets/image/splashScreen.png',
fit: BoxFit.fill,
// height: double.infinity,
// width: double.infinity,
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
alignment: Alignment.center,
repeat: ImageRepeat.noRepeat,
),
]),
),
);
}
}

Resources