AnimatedContainer animates only for one of two elements - flutter

I have an animatedContainer within a Widget, which includes a Container showing a number ("indicator"):
These indicators can increase/decrease or hide and show, but only exlusively. When negative, you see the red one, when positive, you see the green one. When 0, neither is shown.
The issue: The green one animates. The red one unintentionally does not. I have no idea why. It is basically the same widget, only with having empty spacing either on the right or left side, showing a positive or negative value and having either a green or red background color.
Here you see the class handling these "indicators". Keep in mind that in the image above you see two instances of the Widget.
import 'package:flutter/material.dart';
import 'package:progression_flutter/assets/colors.dart';
// TODO: Fix negative indicator unintended disabled animation.
class ProgressIndicators extends StatefulWidget {
const ProgressIndicators(this.valueStream,
{required this.showDigits, Key? key})
: super(key: key);
final Stream<num> valueStream;
final bool showDigits;
#override
State<ProgressIndicators> createState() => _ProgressIndicatorsState();
}
class _ProgressIndicatorsState extends State<ProgressIndicators> {
#override
Widget build(BuildContext context) {
return StreamBuilder<num>(
stream: widget.valueStream,
builder: (BuildContext context, AsyncSnapshot<num> snapshot) {
if (snapshot.hasData) {
final value = snapshot.data;
if (value != null) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 20),
_positionedIndicator(context, value: value),
],
);
}
}
return Container();
},
);
}
Widget _positionedIndicator(BuildContext context, {required num value}) {
final children = [
_animatedIndicator(context, value: value),
];
const spacer = SizedBox(
width: 60,
);
if (value.isNegative) {
children.add(spacer);
} else {
children.insert(0, spacer);
}
return Flexible(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: children,
),
);
}
Widget _animatedIndicator(BuildContext context, {required num value}) {
return AnimatedContainer(
transformAlignment: Alignment.topCenter,
curve: Curves.easeInOut,
height: value == 0 ? 0 : 20,
duration: const Duration(milliseconds: 250),
child: DownHangingProgressIndicator(
value: value,
showDigits: widget.showDigits,
),
);
}
}
class DownHangingProgressIndicator extends StatelessWidget {
const DownHangingProgressIndicator(
{Key? key, required this.value, required this.showDigits})
: super(key: key);
final num value;
final bool showDigits;
#override
Widget build(BuildContext context) {
final isNegative = value.isNegative;
final prefix = value.isNegative ? '' : '+';
final textValue = value.toStringAsFixed(showDigits ? 2 : 0);
return Stack(
alignment: Alignment.center,
children: [
Container(
height: 20,
width: 34,
decoration: BoxDecoration(
color: isNegative
? ProgressionColors.progressionRed
: ProgressionColors.progressionGreen,
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(5),
bottomRight: Radius.circular(5),
),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 2),
child: FittedBox(
fit: BoxFit.scaleDown,
child: Text(
'$prefix$textValue',
style: const TextStyle(color: Colors.white, fontSize: 14),
textHeightBehavior:
const TextHeightBehavior(applyHeightToFirstAscent: false),
),
),
),
),
],
);
}
}
What causes the issue?
Running on iOS, flutter 3.3.4.

Related

Flutter - Add a dashed line as progress indicator for a multi-page Registration flow

The project has 4 registration screens with a dynamic header that displays the current page by the means of color. Below is the state when we move to the first page
Once we complete pages and move on, the indicator for the completed steps changes color and state should be as below
I am able to achieve the icon set and color difference, but I am not able to implement the dashed line between the items. Here are the WIP widgets. Please ignore the icon mismatch
Here's the code for Generating the header
Padding(
padding: const EdgeInsets.only(bottom: 18.0, top: 12),
child: Container(
color: Colors.white,
padding: const EdgeInsets.all(14),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
RegisterStepWidget(
title: "Basic Details",
icon: Drawables.icBasicDetails,
currentStep: currentStep,
stepIndex: 1),
RegisterStepWidget(
title: "Contact Details",
icon: Drawables.icContactDetails,
currentStep: currentStep,
stepIndex: 2),
RegisterStepWidget(
title: "Extra Details",
icon: Drawables.icExtraDetails,
currentStep: currentStep,
stepIndex: 3),
RegisterStepWidget(
title: "Garda Vetting",
icon: Drawables.icBasicDetails,
currentStep: currentStep,
stepIndex: 4),
],
),
),
),
Individual Widget
class RegisterStepWidget extends StatelessWidget {
const RegisterStepWidget(
{Key? key,
required this.title,
required this.icon,
required this.currentStep,
required this.stepIndex})
: super(key: key);
final String title;
final String icon;
final int currentStep;
final int stepIndex;
bool get isCompleted => currentStep > stepIndex;
#override
Widget build(BuildContext context) {
return Column(
children: [
SvgPicture.asset(
icon,
width: 28,
color: isCompleted ? ColorResource.blueGray : ColorResource.darkBlue,
),
const SizedBox(
height: 12,
),
Text(
title,
style: GoogleFonts.notoSans(
fontSize: 12,
color: isCompleted
? ColorResource.blueGray
: ColorResource.darkBlue),
),
],
);
}
}
Change MainAxisAlignment to start and use in middle of widgets
DashLineView(
fillRate: 0.7,
),
.
class DashLineView extends StatelessWidget {
final double dashHeight;
final double dashWith;
final Color dashColor;
final double fillRate; // [0, 1] totalDashSpace/totalSpace
final Axis direction;
DashLineView(
{this.dashHeight = 1,
this.dashWith = 8,
this.dashColor = Colors.black,
this.fillRate = 0.5,
this.direction = Axis.horizontal});
#override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final boxSize = direction == Axis.horizontal
? constraints.constrainWidth()
: constraints.constrainHeight();
final dCount = (boxSize * fillRate / dashWith).floor();
return Flex(
children: List.generate(dCount, (_) {
return SizedBox(
width: direction == Axis.horizontal ? dashWith : dashHeight,
height: direction == Axis.horizontal ? dashHeight : dashWith,
child: DecoratedBox(
decoration: BoxDecoration(color: dashColor),
),
);
}),
mainAxisAlignment: MainAxisAlignment.spaceBetween,
direction: direction,
);
},
);
}
}
Modify accordingly
original credit -> here

Flutter How to stack image and total member text

I was able to show the pictures as in the video by taking advantage of Johannes Milke's video that I left the link of. But that's not all I want. I need a structure that looks like these images but shows the total number of users. I leave the image of exactly what I want and my related codes.
What I want to achieve; Creating a structure where I can write the total number of users
There are a few packages on pub dev but not what I wanted. Thank you
Video:Source Video
image i want to make:
My stacked widget:
import 'package:flutter/material.dart';
class StackedWidgets extends StatelessWidget {
final List<Widget> items;
final TextDirection direction;
final double size;
final double xShift;
const StackedWidgets({
Key? key,
required this.items,
this.direction = TextDirection.ltr,
this.size = 100,
this.xShift = 20,
}) : super(key: key);
#override
Widget build(BuildContext context) {
final allItems = items
.asMap()
.map((index, item) {
final left = size - xShift;
final value = Container(
width: size,
height: size,
child: item,
margin: EdgeInsets.only(left: left * index),
);
return MapEntry(index, value);
})
.values
.toList();
return Stack(
children: direction == TextDirection.ltr
? allItems.reversed.toList()
: allItems,
);
}
}
Usage my stacked widget:
Widget buildStackedImages({
TextDirection direction = TextDirection.ltr,
}) {
final double size = 100;
final double xShift = 20;
final urlImages = [
'https://images.unsplash.com/photo-1554151228-14d9def656e4?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=633&q=80',
'https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80',
'https://images.unsplash.com/photo-1616766098956-c81f12114571?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80',
];
final items = urlImages.map((urlImage) => buildImage(urlImage)).toList();
return StackedWidgets(
direction: direction,
items: items,
size: size,
xShift: xShift,
);
}
Widget buildImage(String urlImage) {
final double borderSize = 5;
return ClipOval(
child: Container(
padding: EdgeInsets.all(borderSize),
color: Colors.white,
child: ClipOval(
child: Image.network(
urlImage,
fit: BoxFit.cover,
),
),
),
);
}
Add a label also to this class
import 'package:flutter/material.dart';
class StackedWidgets extends StatelessWidget {
final List<Widget> items;
final TextDirection direction;
final double size;
final double xShift;
final String lable;
const StackedWidgets({
Key? key,
required this.items,
this.direction = TextDirection.ltr,
this.size = 100,
this.xShift = 20,
this.label = '',
}) : super(key: key);
#override
Widget build(BuildContext context) {
final allItems = items
.asMap()
.map((index, item) {
final left = size - xShift;
final value = Container(
width: size,
height: size,
child: item,
margin: EdgeInsets.only(left: left * index),
);
return MapEntry(index, value);
})
.values
.toList();
return Row(
children: [
Stack(
children: direction == TextDirection.ltr
? allItems.reversed.toList()
: allItems,
),
Text(label),
]
);
}
}
In items pass the number widget and label too
return StackedWidgets(
direction: direction,
items: [...items, Container(
width: 25,//you can also add padding if required
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.orange,
),
child: Text('+22'))],
size: size,
xShift: xShift,
label: "users are here",
);
I will prefer this way,
Run on dartPad
class InTEST extends StatefulWidget {
const InTEST({Key? key}) : super(key: key);
#override
State<InTEST> createState() => _InTESTState();
}
class _InTESTState extends State<InTEST> {
int maxRenderAvatar = 5;
int numberOfActiveUser = 33;
double size = 100;
double borderSize = 5;
Widget buildStackedImages({
TextDirection direction = TextDirection.ltr,
}) {
List<String> urlImages = List.filled(
numberOfActiveUser, //based on your list
'https://images.unsplash.com/photo-1554151228-14d9def656e4?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=633&q=80');
List<Widget> items = [];
final renderItemCount = numberOfActiveUser > maxRenderAvatar
? maxRenderAvatar
: urlImages.length;
for (int i = 0; i < renderItemCount; i++) {
items.add(
Positioned(
left: (i * size * .8),
child: buildImage(
urlImages[i],
),
),
);
}
// add counter if urlImages.length > maxRenderAvatar
if (numberOfActiveUser > maxRenderAvatar) {
items.add(
Positioned(
left: maxRenderAvatar * size * .8,
child: Container(
width: size,
height: size,
padding: EdgeInsets.all(borderSize),
decoration: BoxDecoration(
border: Border.all(color: Colors.white, width: 4),
color: Colors.amber,
shape: BoxShape.circle,
),
alignment: Alignment.center,
child: Text(
"+ ${urlImages.length - maxRenderAvatar}",
style: TextStyle(
fontSize: 23,
),
),
),
),
);
}
return SizedBox(
height: size + (borderSize * 2), //10 for borderSize
width: MediaQuery.of(context).size.width,
child: Stack(
children: items,
),
);
}
Widget buildImage(String urlImage) {
return ClipOval(
child: Container(
padding: EdgeInsets.all(borderSize),
color: Colors.white,
child: ClipOval(
child: Image.network(
urlImage,
width: size,
height: size,
fit: BoxFit.cover,
),
),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Slider(
value: numberOfActiveUser.toDouble(),
min: 0,
max: 55,
onChanged: (v) {
numberOfActiveUser = v.toInt();
setState(() {});
}),
Slider(
value: maxRenderAvatar.toDouble(),
min: 0,
max: 42,
onChanged: (v) {
maxRenderAvatar = v.toInt();
setState(() {});
}),
buildStackedImages(),
],
),
);
}
}

How to give different elements different cross axis alignment in a Flutter Row

The desired outcome is for there to be an icon in the top left corner of the container that stays in place (fixed top, no centering) while a multiline text field expands when the text becomes long, making the container expand. There's also an icon on the right of the container that would be vertically centered.
If it were possible to give different elements in a row different crossAxisAlignment (some start, some center for example) I would be able to solve this problem.
If there was a way to make row elements know and match the height of their tallest sibling, then I could also solve this problem.
I've considered this answer, but the Container that surrounds the Row has a min height and not a max height. When I use SizedBox.expand (as suggested there), I get a BoxConstraints forces an infinite height error. I don't want to give the surrounding container a max height, or force anything to expand to a max height.
I extracted my solution into a VariableCrossAxisAlignmentRow / Column / Flex widget and am posting it.
Here's a screenshot of my example:
And here's the code:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Variable Cross Axis Alignment Flex',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
final _alignments = [
CrossAxisAlignment.start,
CrossAxisAlignment.center,
CrossAxisAlignment.end,
CrossAxisAlignment.stretch,
];
final _flexValues = [1, 2, null, 1];
return Scaffold(
appBar: AppBar(
title: Text('Variable Cross Axis Alignment Flex'),
),
body: Center(
child: Container(
decoration: BoxDecoration(border: Border.all()),
width: 400,
height: 700,
child: VariableCrossAxisAlignmentColumn(
flexValues: _flexValues,
alignments: _alignments,
minWidth: 400,
children: [
Container(
width: 280,
color: Colors.red,
height: Size.infinite.height,
child: Text(
'Flex: ${_flexValues[0]}, ${_alignments[0]}',
style: TextStyle(color: Colors.white),
),
),
Container(
width: 280,
height: Size.infinite.height,
color: Colors.blue,
child: Text(
'Flex: ${_flexValues[1]}, ${_alignments[1]}',
style: TextStyle(color: Colors.white),
),
),
Container(
width: 280,
color: Colors.green,
height: 250,
child: Text(
'Flex: ${_flexValues[2]}, ${_alignments[2]}, height: 250',
style: TextStyle(color: Colors.white),
),
),
Container(
width: 280,
height: Size.infinite.height,
color: Colors.black,
child: Text(
'Flex: ${_flexValues[3]}, ${_alignments[3]}',
style: TextStyle(color: Colors.white),
),
),
]))),
);
}
}
class VariableCrossAxisAlignmentFlex extends StatelessWidget {
final List<int?> flexValues;
final Axis direction;
final List<CrossAxisAlignment> alignments;
final List<Widget> children;
final double crossAxisMinSize;
const VariableCrossAxisAlignmentFlex(
{required this.flexValues,
required this.alignments,
required this.children,
required this.direction,
this.crossAxisMinSize = 0.0,
Key? key})
: super(key: key);
Widget makeAligned(Widget widget, CrossAxisAlignment alignment) {
switch (alignment) {
case CrossAxisAlignment.center:
return Center(
child: widget,
);
case CrossAxisAlignment.start:
return Align(
alignment: _startAlignment(),
child: widget,
);
case CrossAxisAlignment.end:
return Align(
alignment: _endAlignment(),
child: widget,
);
case CrossAxisAlignment.stretch:
return widget;
default:
throw 'Alignment not implemented';
}
}
Alignment _startAlignment() {
if (direction == Axis.horizontal) {
return Alignment.topCenter;
} else {
return Alignment.centerLeft;
}
}
Alignment _endAlignment() {
if (direction == Axis.horizontal) {
return Alignment.bottomCenter;
} else {
return Alignment.centerRight;
}
}
Widget _intrinsicWidget({required Widget child}) {
if (direction == Axis.horizontal) {
return IntrinsicHeight(child: child);
} else {
return IntrinsicWidth(child: child);
}
}
Widget _minSizeWidget() {
if (direction == Axis.horizontal) {
return SizedBox(height: crossAxisMinSize);
} else {
return SizedBox(width: crossAxisMinSize);
}
}
#override
Widget build(BuildContext context) {
assert(flexValues.length == children.length);
assert(alignments.length == children.length);
List<Widget> _children = children.asMap().entries.map((MapEntry entry) {
Widget w = entry.value;
int index = entry.key;
int? flexValue = flexValues[index];
CrossAxisAlignment caa = alignments[index];
Widget _aligned = makeAligned(w, caa);
return flexValue == null
? _aligned
: Flexible(flex: flexValue, child: _aligned);
}).toList();
return _intrinsicWidget(
child: Flex(
direction: direction,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [_minSizeWidget(), ..._children],
),
);
}
}
class VariableCrossAxisAlignmentRow extends VariableCrossAxisAlignmentFlex {
VariableCrossAxisAlignmentRow(
{required List<int?> flexValues,
required List<CrossAxisAlignment> alignments,
required List<Widget> children,
double minHeight = 0.0,
Key? key})
: super(
alignments: alignments,
children: children,
flexValues: flexValues,
direction: Axis.horizontal,
crossAxisMinSize: minHeight);
}
class VariableCrossAxisAlignmentColumn extends VariableCrossAxisAlignmentFlex {
VariableCrossAxisAlignmentColumn(
{required List<int?> flexValues,
required List<CrossAxisAlignment> alignments,
required List<Widget> children,
double minWidth = 0.0,
Key? key})
: super(
alignments: alignments,
children: children,
flexValues: flexValues,
direction: Axis.vertical,
crossAxisMinSize: minWidth);
}

DragTarget doesnt call onWillAccept with custom Draggable (Flutter)

I am trying to make Tags which are draggable text so that I can drag them to one of 2 DragTarget I have (ideally being able to move them between 3 DragTarget). Unfortunately I can't make them interact with the DragTargets as they dont even call onWillAccept(). My draggables are DragabbleTag and extends Draggable and my dragTargets are in a Stateful Widget and should accept them.
import 'package:myApp/components/draggableTag.dart';
import 'package:flutter/material.dart';
class DraggableTagTarget extends StatefulWidget {
final String title;
final int maxTagAmount;
final Color backgroundColor;
final List<DraggableTag> tagsPool;
const DraggableTagTarget(
{Key key,
this.title,
this.backgroundColor,
this.tagsPool,
this.maxTagAmount})
: super(key: key);
#override
_DraggableTagTargetState createState() => _DraggableTagTargetState();
}
class _DraggableTagTargetState extends State<DraggableTagTarget> {
String test = "Test";
#override
Widget build(BuildContext context) {
return DragTarget<DraggableTag>(onAccept: (DraggableTag value) {
setState(() {
widget.tagsPool.add(value);
test = value.label;
});
}, onWillAccept: (DraggableTag data) {
bool result =
widget.tagsPool.length <= widget.maxTagAmount ? true : false;
debugPrint("ONWillAccept: " + data.label + " = " + result.toString());
return result;
}, builder: (context, candidateData, rejectedData) {
return Container(
decoration: new BoxDecoration(
color: widget.backgroundColor,
border: Border.all(
color: Colors.black,
),
),
child: Column(
children: <Widget>[
Text(test),
Text(widget.title),
SizedBox(
height: 60,
child: Wrap(
children: widget.tagsPool,
),
),
],
),
);
});
}
}
Custom DragTarget 'DraggableTagTarget'
import 'package:flutter/material.dart';
class DraggableTag extends Draggable<String> {
final String label;
DraggableTag({Key key, this.label})
: super(
key: key,
data: label,
child: idleTag(label),
feedback: feedbackTag(label),
childWhenDragging: ghostTag(label),
);
static Widget idleTag(String label) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 2.0),
child: Text(
label,
style: TextStyle(
fontSize: 16,
),
),
decoration: BoxDecoration(
color: Colors.blue,
border: Border.all(
color: Colors.black,
),
borderRadius: BorderRadius.all(Radius.circular(20)),
),
);
}
Custom Draggable 'DraggableTag'
I excluded feedbackTag() and ghostTag which shouldnt be relevant
At first my draggableTag was extending a widget but seeing some similar problem I made it into extending directly a Draggable but it didnt help
EDIT:
I am assigning ma values to draggable in a custom DialogWidget (stateful widget) in a list
class _RatingDialogState extends State<RatingDialog> {
List<DraggableTag> tagsPool = [
DraggableTag(label: "Acting"),
DraggableTag(label: "Scenario"),
DraggableTag(label: "Pace"),
DraggableTag(label: "Length"),
DraggableTag(label: "Message"),
];
List<DraggableTag> negativeTagsPool = [];
List<DraggableTag> positiveTagsPool = [];
#override
Widget build(BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
elevation: 0,
backgroundColor: Colors.transparent,
child: contentBox(context),
);
}
contentBox(context) {
return Stack(
...
Wrap(
children: tagsPool,
),
SizedBox(height: 22),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Flexible(
child: FractionallySizedBox(
widthFactor: 0.85,
child: DraggableTagTarget(
title: "Negative",
backgroundColor: Colors.red,
tagsPool: negativeTagsPool,
maxTagAmount: 3),
),
),
Flexible(
child: FractionallySizedBox(
widthFactor: 0.85,
child: DraggableTagTarget(
title: "Positive",
backgroundColor: Colors.green,
tagsPool: positiveTagsPool,
maxTagAmount: 3),
),
),
]),
...
SOLUTION: as ikerfah explained, I didnt put the right type into <> because I was confused to what my DraggableTag class was. I made another class to contains the data Tag so that both my DragTarget and DraggableTag use this class
Draggable and DragTarget must have the same generic type, but you have Draggable<String> and DragTarget<DraggableTag>

Create custom dropdown in flutter - or how to put custom dropdown options in a layer above everything else

I am looking for a way to create a custom dropdown so I can style it myself.
I ran into this answer that seems pretty useful
https://stackoverflow.com/a/63165793/3808307
The problem is that if the container is smaller than the dropdown, flutter complains about pixel overflowing. How can I get this dropdown to be on top of the other elements in the page, so I don't get this warning? Or is there another way to recreate a custom dropdown without this issue?
All answers I find are regarding the built in DropdownButton
Below, the answer linked above, with editions
First, create a dart file named drop_list_model.dart:
import 'package:flutter/material.dart';
class DropListModel {
DropListModel(this.listOptionItems);
final List<OptionItem> listOptionItems;
}
class OptionItem {
final String id;
final String title;
OptionItem({#required this.id, #required this.title});
}
Next, create file file select_drop_list.dart:
import 'package:flutter/material.dart';
import 'package:time_keeping/model/drop_list_model.dart';
import 'package:time_keeping/widgets/src/core_internal.dart';
class SelectDropList extends StatefulWidget {
final OptionItem itemSelected;
final DropListModel dropListModel;
final Function(OptionItem optionItem) onOptionSelected;
SelectDropList(this.itemSelected, this.dropListModel, this.onOptionSelected);
#override
_SelectDropListState createState() => _SelectDropListState(itemSelected, dropListModel);
}
class _SelectDropListState extends State<SelectDropList> with SingleTickerProviderStateMixin {
OptionItem optionItemSelected;
final DropListModel dropListModel;
AnimationController expandController;
Animation<double> animation;
bool isShow = false;
_SelectDropListState(this.optionItemSelected, this.dropListModel);
#override
void initState() {
super.initState();
expandController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 350)
);
animation = CurvedAnimation(
parent: expandController,
curve: Curves.fastOutSlowIn,
);
_runExpandCheck();
}
void _runExpandCheck() {
if(isShow) {
expandController.forward();
} else {
expandController.reverse();
}
}
#override
void dispose() {
expandController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
Container(
padding: const EdgeInsets.symmetric(
horizontal: 15, vertical: 17),
decoration: new BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: Colors.white,
boxShadow: [
BoxShadow(
blurRadius: 10,
color: Colors.black26,
offset: Offset(0, 2))
],
),
child: new Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Icon(Icons.card_travel, color: Color(0xFF307DF1),),
SizedBox(width: 10,),
child: GestureDetector(
onTap: () {
this.isShow = !this.isShow;
_runExpandCheck();
setState(() {
});
},
child: Text(optionItemSelected.title, style: TextStyle(
color: Color(0xFF307DF1),
fontSize: 16),),
),
Align(
alignment: Alignment(1, 0),
child: Icon(
isShow ? Icons.arrow_drop_down : Icons.arrow_right,
color: Color(0xFF307DF1),
size: 15,
),
),
],
),
),
SizeTransition(
axisAlignment: 1.0,
sizeFactor: animation,
child: Container(
margin: const EdgeInsets.only(bottom: 10),
padding: const EdgeInsets.only(bottom: 10),
decoration: new BoxDecoration(
borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20), bottomRight: Radius.circular(20)),
color: Colors.white,
boxShadow: [
BoxShadow(
blurRadius: 4,
color: Colors.black26,
offset: Offset(0, 4))
],
),
child: _buildDropListOptions(dropListModel.listOptionItems, context)
)
),
// Divider(color: Colors.grey.shade300, height: 1,)
],
),
);
}
Column _buildDropListOptions(List<OptionItem> items, BuildContext context) {
return Column(
children: items.map((item) => _buildSubMenu(item, context)).toList(),
);
}
Widget _buildSubMenu(OptionItem item, BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 26.0, top: 5, bottom: 5),
child: GestureDetector(
child: Row(
children: <Widget>[
child: Container(
padding: const EdgeInsets.only(top: 20),
decoration: BoxDecoration(
border: Border(top: BorderSide(color: Colors.grey[200], width: 1)),
),
child: Text(item.title,
style: TextStyle(
color: Color(0xFF307DF1),
fontWeight: FontWeight.w400,
fontSize: 14),
maxLines: 3,
textAlign: TextAlign.start,
overflow: TextOverflow.ellipsis),
),
],
),
onTap: () {
this.optionItemSelected = item;
isShow = false;
expandController.reverse();
widget.onOptionSelected(item);
},
),
);
}
}
Initialize value:
DropListModel dropListModel = DropListModel([OptionItem(id: "1", title: "Option 1"), OptionItem(id: "2", title: "Option 2")]);
OptionItem optionItemSelected = OptionItem(id: null, title: "Chọn quyền truy cập");
Finally use it:
Container(height: 47, child: SelectDropList(
this.optionItemSelected,
this.dropListModel,
(optionItem){
optionItemSelected = optionItem;
setState(() {
});
},
))
Custom dropdown below button
I understand that the built-in dropdown works very well but for some use cases, I need something different. For example, if I only have a few items I want the drop-down to appear below the button or have full control of where the dropdown appears. I haven't found a good option yet so I have tried to make my own. I have built on what #M123 mentioned with the overlay and tried to implement it in a similar way to the built-in dropdown. I have found this medium post from the developer of flutter_typeahead very useful.
https://medium.com/saugo360/https-medium-com-saugo360-flutter-using-overlay-to-display-floating-widgets-2e6d0e8decb9
The button creates a full-screen stack using overlay. This is so that we can add a full-screen gesture detector behind the dropdown so that it closes when the user taps anywhere on the screen.
The overlay is linked to the button using a LayerLink and the CompositedTransformFollower widget.
We also use RenderBox renderBox = context.findRenderObject(); to easily get the position and size of the button. Then position the dropdown accoridingly.
the Dropdown file
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
class CustomDropdown<T> extends StatefulWidget {
/// the child widget for the button, this will be ignored if text is supplied
final Widget child;
/// onChange is called when the selected option is changed.;
/// It will pass back the value and the index of the option.
final void Function(T, int) onChange;
/// list of DropdownItems
final List<DropdownItem<T>> items;
final DropdownStyle dropdownStyle;
/// dropdownButtonStyles passes styles to OutlineButton.styleFrom()
final DropdownButtonStyle dropdownButtonStyle;
/// dropdown button icon defaults to caret
final Icon icon;
final bool hideIcon;
/// if true the dropdown icon will as a leading icon, default to false
final bool leadingIcon;
CustomDropdown({
Key key,
this.hideIcon = false,
#required this.child,
#required this.items,
this.dropdownStyle = const DropdownStyle(),
this.dropdownButtonStyle = const DropdownButtonStyle(),
this.icon,
this.leadingIcon = false,
this.onChange,
}) : super(key: key);
#override
_CustomDropdownState<T> createState() => _CustomDropdownState<T>();
}
class _CustomDropdownState<T> extends State<CustomDropdown<T>>
with TickerProviderStateMixin {
final LayerLink _layerLink = LayerLink();
OverlayEntry _overlayEntry;
bool _isOpen = false;
int _currentIndex = -1;
AnimationController _animationController;
Animation<double> _expandAnimation;
Animation<double> _rotateAnimation;
#override
void initState() {
super.initState();
_animationController =
AnimationController(vsync: this, duration: Duration(milliseconds: 200));
_expandAnimation = CurvedAnimation(
parent: _animationController,
curve: Curves.easeInOut,
);
_rotateAnimation = Tween(begin: 0.0, end: 0.5).animate(CurvedAnimation(
parent: _animationController,
curve: Curves.easeInOut,
));
}
#override
Widget build(BuildContext context) {
var style = widget.dropdownButtonStyle;
// link the overlay to the button
return CompositedTransformTarget(
link: this._layerLink,
child: Container(
width: style.width,
height: style.height,
child: OutlinedButton(
style: OutlinedButton.styleFrom(
padding: style.padding,
backgroundColor: style.backgroundColor,
elevation: style.elevation,
primary: style.primaryColor,
shape: style.shape,
),
onPressed: _toggleDropdown,
child: Row(
mainAxisAlignment:
style.mainAxisAlignment ?? MainAxisAlignment.center,
textDirection:
widget.leadingIcon ? TextDirection.rtl : TextDirection.ltr,
mainAxisSize: MainAxisSize.min,
children: [
if (_currentIndex == -1) ...[
widget.child,
] else ...[
widget.items[_currentIndex],
],
if (!widget.hideIcon)
RotationTransition(
turns: _rotateAnimation,
child: widget.icon ?? Icon(FontAwesomeIcons.caretDown),
),
],
),
),
),
);
}
OverlayEntry _createOverlayEntry() {
// find the size and position of the current widget
RenderBox renderBox = context.findRenderObject();
var size = renderBox.size;
var offset = renderBox.localToGlobal(Offset.zero);
var topOffset = offset.dy + size.height + 5;
return OverlayEntry(
// full screen GestureDetector to register when a
// user has clicked away from the dropdown
builder: (context) => GestureDetector(
onTap: () => _toggleDropdown(close: true),
behavior: HitTestBehavior.translucent,
// full screen container to register taps anywhere and close drop down
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(
children: [
Positioned(
left: offset.dx,
top: topOffset,
width: widget.dropdownStyle.width ?? size.width,
child: CompositedTransformFollower(
offset:
widget.dropdownStyle.offset ?? Offset(0, size.height + 5),
link: this._layerLink,
showWhenUnlinked: false,
child: Material(
elevation: widget.dropdownStyle.elevation ?? 0,
borderRadius:
widget.dropdownStyle.borderRadius ?? BorderRadius.zero,
color: widget.dropdownStyle.color,
child: SizeTransition(
axisAlignment: 1,
sizeFactor: _expandAnimation,
child: ConstrainedBox(
constraints: widget.dropdownStyle.constraints ??
BoxConstraints(
maxHeight: MediaQuery.of(context).size.height -
topOffset -
15,
),
child: ListView(
padding:
widget.dropdownStyle.padding ?? EdgeInsets.zero,
shrinkWrap: true,
children: widget.items.asMap().entries.map((item) {
return InkWell(
onTap: () {
setState(() => _currentIndex = item.key);
widget.onChange(item.value.value, item.key);
_toggleDropdown();
},
child: item.value,
);
}).toList(),
),
),
),
),
),
),
],
),
),
),
);
}
void _toggleDropdown({bool close = false}) async {
if (_isOpen || close) {
await _animationController.reverse();
this._overlayEntry.remove();
setState(() {
_isOpen = false;
});
} else {
this._overlayEntry = this._createOverlayEntry();
Overlay.of(context).insert(this._overlayEntry);
setState(() => _isOpen = true);
_animationController.forward();
}
}
}
/// DropdownItem is just a wrapper for each child in the dropdown list.\n
/// It holds the value of the item.
class DropdownItem<T> extends StatelessWidget {
final T value;
final Widget child;
const DropdownItem({Key key, this.value, this.child}) : super(key: key);
#override
Widget build(BuildContext context) {
return child;
}
}
class DropdownButtonStyle {
final MainAxisAlignment mainAxisAlignment;
final ShapeBorder shape;
final double elevation;
final Color backgroundColor;
final EdgeInsets padding;
final BoxConstraints constraints;
final double width;
final double height;
final Color primaryColor;
const DropdownButtonStyle({
this.mainAxisAlignment,
this.backgroundColor,
this.primaryColor,
this.constraints,
this.height,
this.width,
this.elevation,
this.padding,
this.shape,
});
}
class DropdownStyle {
final BorderRadius borderRadius;
final double elevation;
final Color color;
final EdgeInsets padding;
final BoxConstraints constraints;
/// position of the top left of the dropdown relative to the top left of the button
final Offset offset;
///button width must be set for this to take effect
final double width;
const DropdownStyle({
this.constraints,
this.offset,
this.width,
this.elevation,
this.color,
this.padding,
this.borderRadius,
});
}
using the dropdown
I have tried to make using the custom dropdown similar to the built-in one with the added bonus of being able to style the actual dropdown, as well as the button.
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: CustomDropdown<int>(
child: Text(
'dropdown',
),
onChange: (int value, int index) => print(value),
dropdownButtonStyle: DropdownButtonStyle(
width: 170,
height: 40,
elevation: 1,
backgroundColor: Colors.white,
primaryColor: Colors.black87,
),
dropdownStyle: DropdownStyle(
borderRadius: BorderRadius.circular(8),
elevation: 6,
padding: EdgeInsets.all(5),
),
items: [
'item 1',
'item 2',
'item 3',
'item 4',
]
.asMap()
.entries
.map(
(item) => DropdownItem<int>(
value: item.key + 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(item.value),
),
),
)
.toList(),
),
),
);
}
I am sure there will be some improvements needed in there somewhere. But it's working for me at the moment.
Dropdown decision
I would recommend using the standard Flutter drop down menu. Because it is very robust, easy to write and has been tried and tested. You said that you would like to style your drop down yourself, I suspect that this is the reason why you decided against the standard. But this doesn't have to be the case. The standard drop down menu can be designed pretty well. More on that below
Example Code
String dropdownValue = 'One';
Widget build(BuildContext context) {
return DropdownButton<String>(
value: dropdownValue,
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: <String>['One', 'Two', 'Free', 'Four']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
);
Style
Your DropdownMenuItem will follow your ThemeData class. Not only its backgroundColor will match the canvasColor in your ThemeData class, but also it will follow the same TextStyle.
The Theme data has to be initialized in the Material App:
return MaterialApp(
//....
theme: new ThemeData(
fontFamily: "Encode Sans", //my custom font
canvasColor: _turquoise, //my custom color
//other theme data
),
//.....
),
If you don't want to or can't work with theme data, this may be something for you.
The DropdownButton class has an inbuilt variable called dropdownColor which can be assigned any color you need directly, without changing any ThemeData. Automatically changes the color of the dropdown menu items as well.
For example, if you want to change the With from the dropdown you can feed its child property a new Container and add the desired width. just make sure you use a suitable width so that you do not get overflow problems later on when you use the menu within a more complex layout. I would still recommend leaving the width on dynamic.
In addition, the DropDownButton has the ability to expand, which means that it takes up all the space it can get
DropdownButton<String>(
isExpanded: true,
)
I found a new way to build a custom drop down, by using Overlay.
Docs:
Overlays let independent child widgets "float" visual elements on top
of other widgets by inserting them into the overlay's Stack. The
overlay lets each of these widgets manage their participation in the
overlay using OverlayEntry objects.
This gives you all the design freedom, as every kind of child is allowed. How to move the DropDown I wrote as comments in the code.
Here is a small sample, how to use it.
OverlayEntry floatingDropdown;
AnyButton(
//...
onTap: () {
setState(() {
if (isDropdownOpened) {
floatingDropdown.remove();
} else {
findDropdownData();
floatingDropdown = _createFloatingDropdown();
Overlay.of(context).insert(floatingDropdown);
}
isDropdownOpened = !isDropdownOpened;
});
},
);
OverlayEntry _createFloatingDropdown() {
return OverlayEntry(builder: (context) {
return Positioned(
// You can change the position here
left: xPosition,
width: width,
top: yPosition + height,
height: 4 * height + 40,
// Any child
child: Container(
color: Colors.black,
height: height,
child: Text('Hallo'),
),
);
});
}
A full fully designed example can be found here.
I have improved the answer provided by Dan James with to match 2023.
fixed few issues
added scrollbar for dropdown
added shape customization for dropdown
~ publishing as a answer because there are many pending edits and not responded.
Dropdown class
import 'package:flutter/material.dart';
class CustomDropdown<T> extends StatefulWidget {
/// the child widget for the button, this will be ignored if text is supplied
final Widget child;
/// onChange is called when the selected option is changed.;
/// It will pass back the value and the index of the option.
final void Function(int) onChange;
/// list of DropdownItems
final List<DropdownItem<T>> items;
final DropdownStyle dropdownStyle;
/// dropdownButtonStyles passes styles to OutlineButton.styleFrom()
final DropdownButtonStyle dropdownButtonStyle;
/// dropdown button icon defaults to caret
final Icon? icon;
final bool hideIcon;
/// if true the dropdown icon will as a leading icon, default to false
final bool leadingIcon;
const CustomDropdown({
Key? key,
this.hideIcon = false,
required this.child,
required this.items,
this.dropdownStyle = const DropdownStyle(),
this.dropdownButtonStyle = const DropdownButtonStyle(),
this.icon,
this.leadingIcon = false,
required this.onChange,
}) : super(key: key);
#override
State<CustomDropdown> createState() => _CustomDropdownState();
}
class _CustomDropdownState<T> extends State<CustomDropdown<T>> with TickerProviderStateMixin {
final LayerLink _layerLink = LayerLink();
final ScrollController _scrollController = ScrollController(initialScrollOffset: 0);
late OverlayEntry _overlayEntry;
bool _isOpen = false;
int _currentIndex = -1;
late AnimationController _animationController;
late Animation<double> _expandAnimation;
late Animation<double> _rotateAnimation;
#override
void initState() {
super.initState();
_animationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 200));
_expandAnimation = CurvedAnimation(
parent: _animationController,
curve: Curves.easeInOut,
);
_rotateAnimation = Tween(begin: 0.0, end: 0.5).animate(CurvedAnimation(
parent: _animationController,
curve: Curves.easeInOut,
));
}
#override
Widget build(BuildContext context) {
var style = widget.dropdownButtonStyle;
// link the overlay to the button
return CompositedTransformTarget(
link: _layerLink,
child: Container(
width: style.width,
height: style.height,
padding: style.padding,
decoration: BoxDecoration(
color: style.backgroundColor,
),
child: InkWell(
onTap: _toggleDropdown,
child: Row(
mainAxisAlignment: style.mainAxisAlignment ?? MainAxisAlignment.center,
textDirection: widget.leadingIcon ? TextDirection.rtl : TextDirection.ltr,
mainAxisSize: MainAxisSize.min,
children: [
// if (_currentIndex == -1) ...[
widget.child,
// ]
// else ...[
// widget.items[_currentIndex],
// ],
if (!widget.hideIcon)
RotationTransition(
turns: _rotateAnimation,
child: widget.icon ??
const Padding(
padding: EdgeInsets.only(left: 5, right: 7),
child: RotatedBox(
quarterTurns: 3,
child: Icon(
Icons.arrow_back_ios_rounded,
size: 13,
color: Colors.grey,
),
),
),
),
],
),
),
),
);
}
OverlayEntry _createOverlayEntry() {
// find the size and position of the current widget
RenderBox renderBox = context.findRenderObject()! as RenderBox;
var size = renderBox.size;
var offset = renderBox.localToGlobal(Offset.zero);
var topOffset = offset.dy + size.height + 5;
return OverlayEntry(
// full screen GestureDetector to register when a
// user has clicked away from the dropdown
builder: (context) => GestureDetector(
onTap: () => _toggleDropdown(close: true),
behavior: HitTestBehavior.translucent,
// full screen container to register taps anywhere and close drop down
child: SizedBox(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(
children: [
Positioned(
left: offset.dx,
top: topOffset,
width: widget.dropdownStyle.width ?? size.width,
child: CompositedTransformFollower(
offset: widget.dropdownStyle.offset ?? Offset(0, size.height + 5),
link: _layerLink,
showWhenUnlinked: false,
child: Material(
elevation: widget.dropdownStyle.elevation ?? 0,
color: widget.dropdownStyle.color,
shape: widget.dropdownStyle.shape,
child: SizeTransition(
axisAlignment: 1,
sizeFactor: _expandAnimation,
child: ConstrainedBox(
constraints: widget.dropdownStyle.constraints ??
BoxConstraints(
maxHeight: (MediaQuery.of(context).size.height - topOffset - 15).isNegative
? 100
: MediaQuery.of(context).size.height - topOffset - 15,
),
child: RawScrollbar(
thumbVisibility: true,
thumbColor: widget.dropdownStyle.scrollbarColor ?? Colors.grey,
controller: _scrollController,
child: ListView(
padding: widget.dropdownStyle.padding ?? EdgeInsets.zero,
shrinkWrap: true,
controller: _scrollController,
children: widget.items.asMap().entries.map((item) {
return InkWell(
onTap: () {
setState(() => _currentIndex = item.key);
widget.onChange(item.key);
_toggleDropdown();
},
child: item.value,
);
}).toList(),
),
),
),
),
),
),
),
],
),
),
),
);
}
void _toggleDropdown({bool close = false}) async {
if (_isOpen || close) {
await _animationController.reverse();
_overlayEntry.remove();
setState(() {
_isOpen = false;
});
} else {
_overlayEntry = _createOverlayEntry();
Overlay.of(context)?.insert(_overlayEntry);
setState(() => _isOpen = true);
_animationController.forward();
}
}
}
/// DropdownItem is just a wrapper for each child in the dropdown list.\n
/// It holds the value of the item.
class DropdownItem<T> extends StatelessWidget {
final T? value;
final Widget child;
const DropdownItem({Key? key, this.value, required this.child}) : super(key: key);
#override
Widget build(BuildContext context) {
return child;
}
}
class DropdownButtonStyle {
final MainAxisAlignment? mainAxisAlignment;
final ShapeBorder? shape;
final double elevation;
final Color? backgroundColor;
final EdgeInsets? padding;
final BoxConstraints? constraints;
final double? width;
final double? height;
final Color? primaryColor;
const DropdownButtonStyle({
this.mainAxisAlignment,
this.backgroundColor,
this.primaryColor,
this.constraints,
this.height,
this.width,
this.elevation = 0,
this.padding,
this.shape,
});
}
class DropdownStyle {
final double? elevation;
final Color? color;
final EdgeInsets? padding;
final BoxConstraints? constraints;
final Color? scrollbarColor;
/// Add shape and border radius of the dropdown from here
final ShapeBorder? shape;
/// position of the top left of the dropdown relative to the top left of the button
final Offset? offset;
///button width must be set for this to take effect
final double? width;
const DropdownStyle({
this.constraints,
this.offset,
this.width,
this.elevation,
this.shape,
this.color,
this.padding,
this.scrollbarColor,
});
}
Usage
CustomDropdown<int>(
onChange: (int index) => print("index: $index"),
dropdownButtonStyle: DropdownButtonStyle(
height: 49,
elevation: 1,
backgroundColor: Colors.white,
primaryColor: Colors.black87,
),
dropdownStyle: DropdownStyle(
elevation: 1,
padding: EdgeInsets.all(5),
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.grey,
width: 1,
),
borderRadius: BorderRadius.circular(7))),
items: [
'item 1',
'item 2',
'item 3',
'item 4',
]
.asMap()
.entries
.map(
(item) => DropdownItem<int>(
value: item.key + 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(item.value),
),
),
)
.toList(),
child: Text(
"Item 1",
),
)