How do I stack widgets overlapping each other in flutter - dart

I need to stack widgets like this:
I wrote the code below. However the coins are coming one after another with some default padding. How can I get something like the image above?
Row(
children: <Widget>[
Icon(
Icons.monetization_on, size: 36.0,
color: const Color.fromRGBO(218, 165, 32, 1.0),
),
Icon(
Icons.monetization_on, size: 36.0,
color: const Color.fromRGBO(218, 165, 32, 1.0),
),
],
),

You can use a Stack with Positioned to achieve this:
class StackExample extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(),
body: new Container(
padding: const EdgeInsets.all(8.0),
height: 500.0,
width: 500.0,
// alignment: FractionalOffset.center,
child: new Stack(
//alignment:new Alignment(x, y)
children: <Widget>[
new Icon(Icons.monetization_on, size: 36.0, color: const Color.fromRGBO(218, 165, 32, 1.0)),
new Positioned(
left: 20.0,
child: new Icon(Icons.monetization_on, size: 36.0, color: const Color.fromRGBO(218, 165, 32, 1.0)),
),
new Positioned(
left:40.0,
child: new Icon(Icons.monetization_on, size: 36.0, color: const Color.fromRGBO(218, 165, 32, 1.0)),
)
],
),
),
)
;
}
}
And this how you get some nice shadow drop so the icon stands out more:
class StackExample extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(),
body: new Container(
padding: const EdgeInsets.all(8.0),
height: 500.0,
width: 500.0,
// alignment: FractionalOffset.center,
child: new Stack(
//alignment:new Alignment(x, y)
children: <Widget>[
new Container(
decoration: new BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
boxShadow: [
new BoxShadow(
blurRadius: 5.0,
offset: const Offset(3.0, 0.0),
color: Colors.grey,
)
]
),
child: new Icon(Icons.monetization_on, size: 36.0, color: const Color.fromRGBO(218, 165, 32, 1.0))),
new Positioned(
left: 20.0,
child: new Container(
decoration: new BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
boxShadow: [
new BoxShadow(
blurRadius: 5.0,
offset: const Offset(3.0, 0.0),
color: Colors.grey,
)
]
),
child: new Icon(Icons.monetization_on, size: 36.0, color: const Color.fromRGBO(218, 165, 32, 1.0))),
),
new Positioned(
left:40.0,
child: new Container(
decoration: new BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
boxShadow: [
new BoxShadow(
blurRadius: 5.0,
offset: const Offset(3.0, 0.0),
color: Colors.grey,
)
]
)
,child: new Icon(Icons.monetization_on, size: 36.0, color: const Color.fromRGBO(218, 165, 32, 1.0))),
)
],
),
),
)
;
}
}

As of November 2019 I'd like to add a second solution:
Using package: https://pub.dev/packages/assorted_layout_widgets
var widget1 = ...;
var widget2 = ...;
RowSuper(
children: [widget1, widget2],
innerDistance: -20.0,
);
This will overlap row cells by 20 pixels.
The difference from this solution to the one using Stack is that Positioned widgets in a Stack don't occupy space. So you can't make the Stack the size of its contents, unless you know their sizes in advance. However, the RowSuper will have the size of all of its children widgets.
Note, there is also a ColumnSuper. Also note I am the author of this package.

I wanted something without dependencies and without hardcoded layout.
You could enhance by making overlap use a media query to overlap in terms of %.
Widget overlapped() {
final overlap = 10.0;
final items = [
CircleAvatar(child: Text('1'), backgroundColor: Colors.red),
CircleAvatar(child: Text('2'), backgroundColor: Colors.green),
CircleAvatar(child: Text('3'), backgroundColor: Colors.blue),
];
List<Widget> stackLayers = List<Widget>.generate(items.length, (index) {
return Padding(
padding: EdgeInsets.fromLTRB(index.toDouble() * overlap, 0, 0, 0),
child: items[index],
);
});
return Stack(children: stackLayers);
}

Here is my code on Profile Picture overlapped by camera image in flutter.
Output:
Click here to view output image
Container(
constraints: new BoxConstraints(
maxHeight: 200.0,
maxWidth: 200.0
),
padding: new EdgeInsets.only(left: 16.0, bottom: 8.0, right: 16.0),
decoration: new BoxDecoration(
shape: BoxShape.circle,
image: new DecorationImage(
image: new AssetImage('assets/images/profile.png'),
fit: BoxFit.cover,
),
),
child: Stack(
children: [
new Positioned(
right: 0.0,
bottom: 3.0,
child: Container(
constraints: new BoxConstraints(
maxHeight: 50.0,
maxWidth: 50.0
),
decoration: new BoxDecoration(
boxShadow: [
BoxShadow(
color:Color(0xFFdedede),
offset: Offset(2,2)
),
],
color: Colors.white,
shape: BoxShape.circle,
),
child: GestureDetector(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Icon(
Icons.photo_camera,
size: 34,
color: Color(0xFF00cde7),
),
),
),
),
),
],
),
)

Wraping your elements with OverflowBox and giving the maxWidth value will achieve this effect.
The following can be used in a row or a listview
return SizedBox(
width: 35, //--> list children will be 35 in width
child: OverflowBox(
maxWidth: 50, // --> allowing the child to overflow will cause overlap between elements
child: Container(
width: 50,
child: Text((index + 1).toString()),
),
),
);

You could try my package (signed_spacing_flex). It's exactly the same as a normal Row (or Column and Flex). But it also lets you set negative spacing which causes its children to overlap. You can also set which children should be on top when they overlap.
In your case it would be something like:
SignedSpacingRow(
spacing: -12.0,
stackingOrder: StackingOrder.lastOnTop,
children: <Widget>[
Icon(
Icons.monetization_on, size: 36.0,
color: const Color.fromRGBO(218, 165, 32, 1.0),
),
Icon(
Icons.monetization_on, size: 36.0,
color: const Color.fromRGBO(218, 165, 32, 1.0),
),
],
),
It also works with expanded children if you need.

Reverse variant based on #Lee Higgins
const size = 32.0;
const overlap = size - 6.0;
final containers = [
Container(
decoration: BoxDecoration(
color: Colors.grey[300],
shape: BoxShape.circle,
),
width: size,
height: size,
),
Container(
decoration: BoxDecoration(
color: Colors.grey[400],
shape: BoxShape.circle,
),
width: size,
height: size,
),
];
List<Widget> stackLayers = List<Widget>.generate(containers.length, (index) {
return Padding(
padding: EdgeInsets.fromLTRB(0, 0, index * overlap, 0),
child: containers[index],
);
});
return Stack(alignment: AlignmentDirectional.topEnd, children: stackLayers);

Stack is very much confusing.
The best solution is to use enter link description here

Related

How to make transparent sliverappbar in flutter?

I'm trying to make e-commerce app in flutter.
I wanted to make Appbar transparent and have animation, so I use Sliverappbar but I can't make it transparent without scrolling down.
I tried to use stack, but it doesn't work and has error.
I want appbar transparent when it's on top and change white when I scroll down.
This is my flutter code
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: true,
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0.0,
leading: Icon(
Icons.menu,
size: 30,
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.tune, color: Colors.black, size: 30),
)
],
),
body: _buildBody(),
);
}
Widget _buildBody() {
return CustomScrollView(
slivers: <Widget>[
SliverAppBar(
leading: Icon(
Icons.menu,
size: 30,
),
backgroundColor: Colors.transparent,
actions: <Widget>[
IconButton(
icon: Icon(
Icons.tune,
color: Colors.black,
size: 30,
),
)
],
floating: true,
elevation: 0.0,
snap: false,
),
SliverToBoxAdapter(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.7,
width: MediaQuery.of(context).size.width,
child: Carousel(
images: [
Image.network(
'https://i.pinimg.com/564x/83/32/37/8332374f18162612dd9f2a4af2fda794.jpg',
fit: BoxFit.cover),
Image.network(
'https://i.pinimg.com/originals/e2/8e/50/e28e5090b7193ec9b2d5b5c6dfaf501c.jpg',
fit: BoxFit.cover),
Image.network(
'https://image-cdn.hypb.st/https%3A%2F%2Fhypebeast.com%2Fwp-content%2Fblogs.dir%2F6%2Ffiles%2F2019%2F09%2Fmschf-fall-winter-lookbook-streetwear-seoul-korea-47.jpg?q=75&w=800&cbr=1&fit=max',
fit: BoxFit.cover)
],
showIndicator: false,
)),
),
SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.only(
left: 25.0, top: 20.0, right: 0.0, bottom: 20.0),
child: Text('Recommended for You',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 25)),
),
),
SliverPadding(
padding: EdgeInsets.only(left: 35.0, right: 35.0),
sliver: SliverGrid(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 20.0,
crossAxisSpacing: 25.0,
childAspectRatio: 0.67,
),
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return _buildListItem(context, index);
},
childCount: 13,
),
))
],
);
Best solution I can find is, instead of using SliverAppBar, use a regular AppBar in a SliverToBoxAdapter. You would set the flexibleSpace property to your Carousel, or put the AppBar and carousel into a Stack.
The flexibleSpace property, as far as I can tell, behaves differently in a SliverAppBar and a regular AppBar. It wont collapse in a regular AppBar and you also won't need to put your carousel in a FlexibleSpaceBar().
You may need to do a few additional things to get the exact look you're going for (e.g. change the elevation).
You can simply warp SliverAppBar with SliverOpacity widget
SliverOpacity (
opacity: 0.5,
sliver: SliverAppBar(
leading: Icon(
Icons.menu,
size: 30, ),
backgroundColor: Colors.transparent,
actions: <Widget>[
IconButton(
icon: Icon(
Icons.tune,
color: Colors.black,
size: 30,
),
)
],
floating: true,
elevation: 0.0,
snap: false,
),
)

How to animate custom AppBar in Flutter?

I don't have much experience in flutter yet, and I curious of how can I achieved custom AppBar that can be animated.
I just want to apply a simple animation to the AppBar which will only change the height of the AppBar. As I understand that the AppBar must be a PreferredSizeWidget and I want to animate it to change the height, there are couple articles that I read but mostly it uses SilverAppBar.
Thanks.
class CustomAppBarRounded extends StatelessWidget implements PreferredSizeWidget{
final String _appBarTitle;
CustomAppBarRounded(this._appBarTitle);
#override
Widget build(BuildContext context) {
return new Container(
child: new LayoutBuilder(builder: (context, constraint) {
final width = constraint.maxWidth * 8;
return new ClipRect(
child: Stack(
children: <Widget>[
new OverflowBox(
maxHeight: double.infinity,
maxWidth: double.infinity,
child: new SizedBox(
width: width,
height: width,
child: new Padding(
padding: new EdgeInsets.only(
bottom: width / 2 - preferredSize.height / 3
),
child: new DecoratedBox(
decoration: new BoxDecoration(
color: Colors.indigo,
shape: BoxShape.circle,
boxShadow: [
new BoxShadow(color: Colors.black54, blurRadius: 10.0)
],
),
),
),
),
),
new Center(
child: new Text("${this._appBarTitle}",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white,
shadows: [
Shadow(color: Colors.black54, blurRadius: 10.0)
]
),
)
),
],
)
);
}),
);
}
#override
Size get preferredSize => const Size.fromHeight(100.0);
}
I've figured out how to achieve what I wanted. So I returned the PreferredSizeWidget
class CustomRoundedAppBar extends StatelessWidget{
double height = 100;
final String title;
CustomRoundedAppBar(
this.height,
this.title);
#override
Widget build(BuildContext context) {
return PreferredSize(
preferredSize: Size(this.height, this.height),
child: AnimatedContainer(
duration: Duration(seconds: 1),
height: this.height,
child: new LayoutBuilder(builder: (context, constraint){
final width =constraint.maxWidth * 8;
return new ClipRect(
child: Stack(
children: <Widget>[
new OverflowBox(
maxHeight: double.infinity,
maxWidth: double.infinity,
child: new SizedBox(
width: width,
height: width,
child: new Padding(
padding: new EdgeInsets.only(
bottom: width / 2 - this.height / 3
),
child: new DecoratedBox(
decoration: new BoxDecoration(
color: Colors.indigo,
shape: BoxShape.circle,
boxShadow: [
new BoxShadow(color: Colors.black54, blurRadius: 10.0)
],
),
),
),
),
),
new Center(
child: new Text("${this.title}",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white,
shadows: [
Shadow(color: Colors.black54, blurRadius: 10.0)
]
),
)
),
],
)
);
})
),
);
}
}
And on the Scaffold I have an action when button is pressed it will change the height, which must be on the setState()
onPressed: (){
setState(() {
this.height = 200;
this. _appBarTitle = "TEST";
});
},

How can I add shadow to an icon in flutter?

I need to add shadows to some icons in my flutter project. I've checked the icon class constructors but nothing points to that. Any idea on how to implement that?
I got what i wanted eventually using this workaround. I hope it helps whoever might need something similar.
Stack(
children: <Widget>[
Positioned(
left: 1.0,
top: 2.0,
child: Icon(icon, color: Colors.black54),
),
Icon(icon, color: Colors.white),
],
),
The Icon widget has a shadows property with which you can give shadows to an icon.
const Icon(
icon,
shadows: <Shadow>[Shadow(color: Colors.black, blurRadius: 15.0)],
size: 60,
color: Colors.white,
)
Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: Colors.grey[400],
blurRadius: 5.0,
),
]
),
child: Icon(
Icons.fiber_manual_record,
color: Colors.amber,
size:15,
)
),
You can use IconShadowWidget().
How to use:
1. add dependencies to pubspec.yaml:
icon_shadow: ^1.0.1
2. Import your Dart code :
import 'package:icon_shadow/icon_shadow.dart';
3. add icons:
Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
IconShadowWidget(
Icon(
Icons.add_circle,
color: Colors.red,
size: 100.0,
),
),
IconShadowWidget(
Icon(
Icons.add_circle,
color: Colors.red,
size: 100.0,
),
shadowColor: Colors.black,
),
IconShadowWidget(
Icon(
Icons.add_circle,
color: Colors.red,
size: 100.0,
),
shadowColor: Colors.black,
showShadow: false,
),
],
),
),
You can also check my GitHub Repository
Whenever you need elevation/shadow, remember the Card widget. So, you can wrap it with Card and SizedBox:
Card(
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(35.0),
),
child: SizedBox(
width: 35,
height: 35,
child: Icon(
Icons.close,
color: Colors.black,
size: 19,
),
),
)
Even better, here is an icon button with material bubble effect + shadow (in below GIF, shadow's quality looks like bad, it is because of GIF itself)
:
Card(
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(35.0),
),
child: ClipOval(
child: Material(
color: Colors.transparent, // button color
child: InkWell(
splashColor: Colors.red, // inkwell color
child: SizedBox(
width: 35,
height: 35,
child: Icon(
Icons.close,
color: Colors.black,
size: 19,
),
),
onTap: () {},
),
),
),
)
Took the idea from #Dzeri answer (https://stackoverflow.com/a/55668093/414635) and encapsulated it into a Widget so it became reusable.
Widget
class ShadowIcon extends StatelessWidget {
final IconData icon;
final Color color;
ShadowIcon(this.icon, {Key key, this.color: kLight}) : super(key: key);
#override
Widget build(BuildContext context) {
return Stack(
children: [
Positioned(
left: 0.5,
top: 0.5,
child: BackdropFilter(
filter: ImageFilter.blur(
sigmaX: 1.0,
sigmaY: 1.0,
),
child: FaIcon(this.icon, color: kDark.withOpacity(0.7)),
),
),
FaIcon(this.icon, color: color),
],
);
}
}
The BackdropFilter doesn't seem to be working as expected but anyway all I needed was a subtle drop shadow. I'm also using the package font_awesome_flutter but you can replace the FaIcon by the native Icon widget.
Usage
Your can simply replace the native Icon by the ShadowIcon widget call:
IconButton(
icon: ShadowIcon(FontAwesomeIcons.chevronLeft, color: kLight),
onPressed: () => Get.back(),
),
InkWell(
child: Container(
padding: const EdgeInsets.all(4.0),
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: Colors.grey,
blurRadius: .5,
),
]),
child: Icon(
Icons.clear,
color: Colors.black,
size: 25,
)),
),
result will be like this pic:
:
Right now, it's not possible to directly add shadows to an Icon widget. You can however use the additional information from your IconData icon to display the icon as a styled text.
Text(
String.fromCharCode(Icons.add.codePoint),
style: TextStyle(
fontFamily: Icons.add.fontFamily,
color: Colors.white,
fontSize: 20.0,
shadows: [
BoxShadow(
color: ColorTheme.blackLight,
spreadRadius: 2,
blurRadius: 2,
)
],
height: 1 //if this isn't set, the shadow will be cut off on the top and bottom
)
);
Try this, use the icon font.
GestureDetector(
child: Container(
padding: EdgeInsets.only(right: 10, top: 10),
child: Text('\u{e5d3}',
style: TextStyle(
fontSize: 22,
color: Colors.white,
fontFamily: 'MaterialIcons',
shadows: [
BoxShadow(color: Colors.black, blurRadius: 2)
])),
),
onTap: () {}
)
Icon data from icons.dart
/// <i class="material-icons md-36">more_horiz</i> — material icon named "more horiz".
static const IconData more_horiz = IconData(0xe5d3, fontFamily: 'MaterialIcons');
You can use decorated icon plugin to do shadow on icon
Code here :
Scaffold(
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
DecoratedIcon(
Icons.android,
color: Colors.purple,
size: 60.0,
shadows: [
BoxShadow(
blurRadius: 42.0,
color: Colors.purpleAccent,
),
BoxShadow(
blurRadius: 12.0,
color: Colors.white,
),
],
),
DecoratedIcon(
Icons.favorite,
color: Colors.lightBlue.shade50,
size: 60.0,
shadows: [
BoxShadow(
blurRadius: 12.0,
color: Colors.blue,
),
BoxShadow(
blurRadius: 12.0,
color: Colors.green,
offset: Offset(0, 6.0),
),
],
),
DecoratedIcon(
Icons.fingerprint,
color: Colors.orange,
size: 60.0,
shadows: [
BoxShadow(
color: Colors.black,
offset: Offset(3.0, 3.0),
),
],
),
],
),
),
);
I know this is pretty late, but for anyone looking to add a shadow in circular form should wrap the icon with a CircleAvatar widget and set the backgroundColor proprety of CircleAvatar to Colors.grey.withOpacity (0.5) or to any other color for the shadow. Here's the code snippet
CircleAvatar (
bacgroundColor: Colors.grey.withOpacity (0.5),
child: Icon (
Icons.yourIcon
)
Material(
color: Colors.transparent,
elevation: 10,
child: Icon(
icons.add,
),
),
Container(
width: 30,
height: 30,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(100),
boxShadow: const [
BoxShadow(color: Colors.grey, blurRadius: 1),
],
),
child: const Icon(
FontAwesomeIcons.checkCircle,
size: 30,
color: Colors.green,
),
),
If the container size is the same as the icon size, then 3 pixels will be always downward, This is because I don't know. but this solution will clear it.
Make sure that the container size will increase by 3 pixels with icons size.
Container(
width: 33,
height: 33,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(100),
boxShadow: const [
BoxShadow(color: Colors.grey, blurRadius: 1),
]),
child: const Icon(
FontAwesomeIcons.checkCircle,
size: 30,
color: Colors.green,
),
),
base on this answer you can use this code and maybe add some change
import 'package:flutter/material.dart';
class IconShadowView extends Icon {
const IconShadowView(super.icon,
{super.key,
super.color,
super.semanticLabel,
super.shadows,
super.size,
super.textDirection});
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Positioned(
left: 1.0,
top: 2.0,
child: Icon(
icon,
color: Colors.black,
key: key,
semanticLabel: semanticLabel,
shadows: shadows,
size: size,
textDirection: textDirection,
),
),
super.build(context),
],
);
}
}

How to set width to Material widget on Flutter?

I've a Material widget to wrap a MaterialButton to make border radius, but I can't set the width attribute to it. I tried use a SizedBox but not works, the Material widget keep using all space of screen.
Code:
return new SizedBox(
width: 40,
child: Material(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(22.0)),
elevation: 18.0,
color: Color(0xFF801E48),
clipBehavior: Clip.antiAlias,
child: MaterialButton(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
height: 30.0,
child: new Text('Sair',
style:
new TextStyle(fontSize: 16.0, color: Colors.white)),
),
),
);
Result:
Clearly it not have 40.0 of width size.
A better approach is using Container widget. When you need to change width, height or add padding/margin to any widget you should wrap the target widget into a container. The container widget is for this kind of job.
Container(
width: myWidthValue, // Container child widget will get this width value
height: myHeghtValue, // Container child widget will get this height value
padding: allowPaddingToo, // padding is allowed too
child: Material(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(22.0)),
elevation: 18.0,
color: Color(0xFF801E48),
clipBehavior: Clip.antiAlias, // Add This
child: MaterialButton(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
height: 30.0,
child: new Text('Sair',
style:
new TextStyle(fontSize: 16.0, color: Colors.white)),
onPressed: () {
setState(() {
_isNeedHelp = false;
});
},
),
),
);
This is how you can set the size, padding, and margin of widgets in general. here is an example for Button:
Container(
margin: EdgeInsets.only(top: 10), // Top Margin
child:
ElevatedButton(
style: TextButton.styleFrom(
// Inside Padding
padding: EdgeInsets.symmetric(horizontal: 0, vertical: 20),
// Width,Height
minimumSize: Size(300, 30),
),
child: Text('Upload Data'),
onPressed: () {submitForm();},
),
),
Solved using Padding:
return Padding(
padding: EdgeInsets.fromLTRB(50, 0, 50, 0),
child: Material(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(22.0)),
elevation: 18.0,
color: Color(0xFF801E48),
clipBehavior: Clip.antiAlias, // Add This
child: MaterialButton(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
height: 30.0,
child: new Text('Sair',
style:
new TextStyle(fontSize: 16.0, color: Colors.white)),
onPressed: () {
setState(() {
_isNeedHelp = false;
});
},
),
),
);
Result:

Flutter - changing a Stack Order

I have a Stack where on a condition (e.g. user click), I want one of the lower order widgets to be pushed to the top of the stack. Using the code below as a simple example - what code do I need in a setState() method to reorder so that the first (bottom) widget becomes the last (top) widget?
new Stack(
children: <Widget>[
new Icon(Icons.monetization_on, key: GlobalKey(), size: 60.0, color: const
Color.fromRGBO(200, 100, 180, 1.0)),
new Positioned(
left: 20.0,
child: new Icon(Icons.monetization_on, key: GlobalKey(), size: 60.0, color: const
Color.fromRGBO(000, 10, 130, 1.0)),
),
new Positioned(
left:40.0,
child: new Icon(Icons.monetization_on, key: GlobalKey(), size: 60.0, color: const Color.fromRGBO(218, 165, 32, 1.0)),
)
],
);
I have edited the proposed solution and the stack does not change order. Here is the sample code in full (the print statement print to the console as expected on button press):
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
AnimationController timerController;
void main() => runApp(MaterialApp(
home: MyApp(),
));
class MyApp extends StatefulWidget {
#override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
AnimationController timerController;
#override
Widget build(BuildContext context) {
List<Widget> stackChildren = <Widget>[
new Icon(Icons.monetization_on,
key: GlobalKey(),
size: 60.0,
color: const Color.fromRGBO(50, 50, 50, 1.0)),
new Positioned(
left: 20.0,
child: new Icon(Icons.monetization_on,
key: GlobalKey(),
size: 60.0,
color: const Color.fromRGBO(50, 100, 150, 1.0)),
),
];
void swapStackChildren() {
setState(() {
print("swapStackChildren");
stackChildren = [
new Positioned(
left: 40.0,
child: new Icon(Icons.monetization_on,
key: GlobalKey(),
size: 60.0,
color: const Color.fromRGBO(150, 00, 200, 1.0))),
new Icon(Icons.monetization_on,
key: GlobalKey(),
size: 100.0,
color: const Color.fromRGBO(200, 200, 100, 1.0)),
];
});
}
return Scaffold(
body: Padding(
padding: EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Stack(children: stackChildren),
new RaisedButton(
child: const Text('Swop'),
color: Theme.of(context).accentColor,
elevation: 4.0,
splashColor: Colors.blueGrey,
onPressed: () {
swapStackChildren();
},
),
],
),
),
);
}
}
Make a variable in your widget that keeps track of the children:
List<Widget> stackChildren = <Widget>[
new Icon(Icons.monetization_on, key: GlobalKey(), size: 60.0, color: const
Color.fromRGBO(200, 100, 180, 1.0)),
new Positioned(
left: 20.0,
child: new Icon(Icons.monetization_on, key: GlobalKey(), size: 60.0, color: const
Color.fromRGBO(000, 10, 130, 1.0)),
),
new Positioned(
left:40.0,
child: new Icon(Icons.monetization_on, key: GlobalKey(), size: 60.0, color: const Color.fromRGBO(218, 165, 32, 1.0)),
)
];
Then in whatever function you have to trigger the order switch, you can just call the following function:
void swapStackChildren() {
final temp = stackChildren[0];
setState(() {
stackChildren[0] = stackChildren[2];
stackChildren[2] = temp;
});
}
Edit: As suggested by the comments, it's a better idea just to assign a new value to stackChildren instead of modifying it. So you should instead do something like this:
void swapStackChildren() {
setState(() {
stackChildren = [
new Positioned(
left: 40.0,
child: new Icon(Icons.monetization_on,
key: GlobalKey(),
size: 60.0,
color: const Color.fromRGBO(218, 165, 32, 1.0))),
new Icon(Icons.monetization_on,
key: GlobalKey(),
size: 60.0,
color: const Color.fromRGBO(200, 100, 180, 1.0)),
new Positioned(
left: 20.0,
child: new Icon(Icons.monetization_on,
key: GlobalKey(),
size: 60.0,
color: const Color.fromRGBO(000, 10, 130, 1.0)),
),
];
});
}
Edit:
Here is with the full sample code:
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
AnimationController timerController;
void main() => runApp(MaterialApp(
home: MyApp(),
));
class MyApp extends StatefulWidget {
#override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
AnimationController timerController;
List<Widget> stackChildren = <Widget>[
new Icon(Icons.monetization_on,
key: GlobalKey(),
size: 60.0,
color: const Color.fromRGBO(50, 50, 50, 1.0)),
new Positioned(
left: 20.0,
child: new Icon(Icons.monetization_on,
key: GlobalKey(),
size: 60.0,
color: const Color.fromRGBO(50, 100, 150, 1.0)),
),
];
void swapStackChildren() {
setState(() {
print("swapStackChildren");
stackChildren = [
new Positioned(
left: 40.0,
child: new Icon(Icons.monetization_on,
key: GlobalKey(),
size: 60.0,
color: const Color.fromRGBO(150, 00, 200, 1.0))),
new Icon(Icons.monetization_on,
key: GlobalKey(),
size: 100.0,
color: const Color.fromRGBO(200, 200, 100, 1.0)),
];
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Stack(children: stackChildren),
new RaisedButton(
child: const Text('Swop'),
color: Theme.of(context).accentColor,
elevation: 4.0,
splashColor: Colors.blueGrey,
onPressed: () {
swapStackChildren();
},
),
],
),
),
);
}
}
I've found a less code intensive solution .You can use the Visibility widget which you can control the visibility of the child widget after the change of state .
Visibility(
visible:visibility,//it takes bool
//here you can add the bottom widget that you want on top keeping it invisible
),
make a copy of your bottom widget and add it on top wrapped in the Visibility method as invisible and wrap your bottom widget as well .So when you want to switch you can make your bottom widget invisible and your top visible and switch accordingly
new Stack(
children: <Widget>[
Visibility(
visible:topvisibility
new Positioned(
left:40.0,
child: new Icon(Icons.monetization_on, key: GlobalKey(), size: 60.0, color: const Color.fromRGBO(218, 165, 32, 1.0)),
)
),
new Icon(Icons.monetization_on, key: GlobalKey(), size: 60.0, color: const
Color.fromRGBO(200, 100, 180, 1.0)),
new Positioned(
left: 20.0,
child: new Icon(Icons.monetization_on, key: GlobalKey(), size: 60.0, color: const
Color.fromRGBO(000, 10, 130, 1.0)),
),
Visibility(
visible:bottomvisibility
new Positioned(
left:40.0,
child: new Icon(Icons.monetization_on, key: GlobalKey(), size: 60.0, color: const Color.fromRGBO(218, 165, 32, 1.0)),
)
),
],
);
Then change the visibility bool accordingly in setState() method.
You can refer to this article about reordering stack items- LINK
Also don't forget to assign keys to the stack widgets if you don't want to re-render the whole widget when setState(){} is called.

Resources