Flutter - change appbar icon when receiving notification - android

I am using FirebaseMessaging to push notifications on my app.
So I can handle these notification with this code :
firebaseMessaging.configure(
onLaunch: (Map<String, dynamic> msg) {
print("onLaunch called");
}, onResume: (Map<String, dynamic> msg) {
print("onResume called");
}, onMessage: (Map<String, dynamic> msg) {
print("onMessage called : " + msg.toString());
});
When I receive a notification, I want to display this little '1' on my icon in my appbar
My problem is : I don't know how to change my bell icon dynamically on my appbar for all pages (and I can't call setState in my appbar)

I think is pretty simple to solve your problem you only need to use a Stateful class and a custom icon as below snippet:
Widget myAppBarIcon(){
return Container(
width: 30,
height: 30,
child: Stack(
children: [
Icon(
Icons.notifications,
color: Colors.black,
size: 30,
),
Container(
width: 30,
height: 30,
alignment: Alignment.topRight,
margin: EdgeInsets.only(top: 5),
child: Container(
width: 15,
height: 15,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Color(0xffc32c37),
border: Border.all(color: Colors.white, width: 1)),
child: Padding(
padding: const EdgeInsets.all(0.0),
child: Center(
child: Text(
_counter.toString(),
style: TextStyle(fontSize: 10),
),
),
),
),
),
],
),
);
}
and later you can include this icon on your app bar(leading or action). As you can see the Text value change with any touch I used as base the example code when you start a new Flutter project it contains a method to count how many times you touch the floating button and change the state:
void _incrementCounter() {
setState(() {
_counter++;
});
}
I hope this helps you
this is my example

Basic Idea behind the notification badge
Using Stack and Positioned widgets we can stack the Text widget over the
IconButton to show the notification badge.
appBar: AppBar(
leading: IconButton(
icon: Icon(
_backIcon(),
color: Colors.black,
),
alignment: Alignment.centerLeft,
tooltip: 'Back',
onPressed: () {
},
),
title: Text(
"Title",
style: TextStyle(
color: Colors.black,
),
),
backgroundColor: Colors.white,
actions: <Widget>[
IconButton(
tooltip: 'Search',
icon: const Icon(
Icons.search,
color: Colors.black,
),
onPressed: _toggle,
),
new Padding(
padding: const EdgeInsets.all(10.0),
child: new Container(
height: 150.0,
width: 30.0,
child: new GestureDetector(
onTap: () {
},
child: Stack(
children: <Widget>[
new IconButton(
icon: new Icon(
Icons.shopping_cart,
color: Colors.black,
),
onPressed: () {
}),
ItemCount == 0
? new Container()
: new Positioned(
child: new Stack(
children: <Widget>[
new Icon(Icons.brightness_1,
size: 20.0, color: Colors.orange.shade500),
new Positioned(
top: 4.0,
right: 5.0,
child: new Center(
child: new Text(
ItemCount.toString(),
style: new TextStyle(
color: Colors.white,
fontSize: 11.0,
fontWeight: FontWeight.w500),
),
)),
],
)),
],
),
),
),
)
],
),

You have to create a custom drawable and set it as the Appbar icon and you have to paint the number as text in the custom drawable. This is already done for you in the following link.
How to make an icon in the action bar with the number of notification?

you can just create variable of type IconData and change it's value. you will get more idea about that after gone through below example.
import 'package:flutter/material.dart';
void main() => runApp(MyHome());
class MyHome extends StatefulWidget {
#override
_MyHomeState createState() => _MyHomeState();
}
class _MyHomeState extends State<MyHome> {
IconData _iconData= Icons.notifications;
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primaryColor: Color(0xffFF5555),
),
home: Scaffold(
appBar: new AppBar(
title: new Text("Title"),
actions: <Widget>[
Icon(_iconData)
],
),
body: Center(
child: new Text("Demo")
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.check_circle_outline),
onPressed: (){
if(_iconData == Icons.notifications){
setState(() {
_iconData = Icons.notifications_active;
});
}else{
setState(() {
_iconData = Icons.notifications;
});
}
}
),
),
);
}
}

Related

IconButton widget in my flutter app takes 2-3 seconds to render. Why does this happen?

I am a flutter newbie. I have two IconButtons in my android flutter app. When i run the app the two IconButtons take 2 seconds to render after all other components have rendered.
This is my code, The IconButtons are used in the end:
class MyHomePageState extends State<MyHomePage> {
late Widget _iconButton1;
late Widget _iconButton2;
#override
void initState() {
_iconButton1 = IconButton(
padding: const EdgeInsets.all(0),
iconSize: 80,
onPressed: () {
setTime();
setState(() {});
},
icon: Image.asset("assets/reset_big.png"),
);
_iconButton2 = IconButton(
padding: const EdgeInsets.all(0),
iconSize: 80,
onPressed: () {
datePicker();
setState(() {});
},
icon: Image.asset("assets/calendar_big.png"),
);
super.initState();
count();
setState(() {});
}
#override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/bgimg.jpg"), fit: BoxFit.cover),
),
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
title: Column(
children: <Widget>[
const SizedBox(
height: 20,
),
Text(
widget.title,
style: const TextStyle(
fontFamily: 'Poppins', fontSize: 40, color: Colors.white60),
),
],
),
elevation: 0,
backgroundColor: Colors.transparent,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Stack(
alignment: Alignment.center,
children: [
BlurryContainer(
blur: 0,
height: 150,
width: 150,
color: Colors.transparent,
borderRadius: const BorderRadius.all(Radius.circular(100)),
child: Center(
child: Text(
'$curr',
style: const TextStyle(
fontFamily: 'Rubik',
fontSize: 80,
color: Color.fromARGB(255, 240, 238, 243)),
),
),
),
],
),
],
),
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Container(
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.transparent,
),
child: _iconButton1),
const SizedBox(
height: 10,
),
_iconButton2
FloatingActionButton(onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => SettingsScreen()));
})
],
),
),
);
}
}
and when i debug the app i get this in the console. Don't know if its related to the issue.
I/MSHandlerLifeCycle(16618): isMultiSplitHandlerRequested: windowingMode=1 isFullscreen=true isPopOver=false isHidden=false skipActivityType=false isHandlerType=true this: DecorView#fe2bf28[MainActivity]
I thought it was because the widgets were being rebuilt and changed my code as this post says Prevent widget from being rebuilt
But it has no effect.
I want the buttons to render just like the other components do.
Your image sizes are probably too large.
"assets/calendar_big.png"
"assets/reset_big.png"
Please check the sizes.
Also, pre cache the image like this inside initState
precacheImage(AssetImage("assets/calendar_big.png"), context);
precacheImage(AssetImage("assets/reset_big.png"), context);
Why are you initializing the widgets inside initState?
Remove these from initState
_iconButton1 = IconButton(
padding: const EdgeInsets.all(0),
iconSize: 80,
onPressed: () {
setTime();
setState(() {});
},
icon: Image.asset("assets/reset_big.png"),
);
_iconButton2 = IconButton(
padding: const EdgeInsets.all(0),
iconSize: 80,
onPressed: () {
datePicker();
setState(() {});
},
icon: Image.asset("assets/calendar_big.png"),
);
Add them directly where they are needed in place of _iconButton1 and _iconButton2.
child: _iconButton1
_iconButton2

How i can create dropdown like this in flutter

Hey guys I'm working on some project and need to create a custom dropdown,
like this
I am able to make that here is the code, the code is messy but I will refactor it once I make it work. Or if you have some other way how I can accomplish this I'm open to suggestions.
GlobalKey? actionKey = GlobalKey();
List<String> picked = [];
List<IconData> icons = [
Icons.blur_circular_outlined,
Icons.sports_basketball,
Icons.sports_baseball_sharp,
Icons.sports_tennis_rounded,
Icons.people,
];
List<String> sports = [
"Fudbal",
"Kosarka",
"Tenis",
"Stoni tenis",
"Kuglanje"
];
List<int> ints = [0, 1, 2, 3, 4];
List<bool> booles = [false, false, false, false, false];
OverlayEntry? overlayEntry;
var position;
double? y;
double? x;
void findDropdownData() {
RenderBox renderBox =
actionKey!.currentContext!.findRenderObject() as RenderBox;
position = renderBox.localToGlobal(Offset.zero);
y = position!.dy;
x = position!.dx;
}
OverlayEntry _overlayEntryBuilder() {
return OverlayEntry(
builder: (context) {
return Positioned(
// top: position,
left: 16.w,
right: 16.w,
child: Material(
child: dropdownExpanded(),
),
);
},
);
}
Widget buildRows(i) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 17.w, vertical: 15.h),
child: Row(
children: [
SizedBox(
height: 24.h,
width: 24.w,
child: Checkbox(
activeColor: style.purpleMain,
value: booles[i],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4)),
onChanged: (value) {
setState(() {
booles[i] = value!;
booles[i] == true
? picked.add(sports[i])
: picked.remove(sports[i]);
});
},
),
),
SizedBox(
width: 10.w,
),
Text(
sports[i],
style: TextStyle(
color: booles[i] == true ? style.purpleMain : Colors.grey,
),
),
const Spacer(),
Icon(
icons[i],
color: booles[i] == true ? style.purpleMain : Colors.grey,
size: 15,
),
],
),
);
}
Widget dropdown() {
return GestureDetector(
key: actionKey,
onTap: () {
setState(() {
isPressed = !isPressed;
});
if (isPressed == false) {
overlayEntry = _overlayEntryBuilder();
Overlay.of(context)!.insert(overlayEntry!);
}
},
child: Container(
width: double.infinity,
height: 50.h,
decoration: BoxDecoration(
border: Border.all(color: style.e8e8e8),
borderRadius: BorderRadius.circular(8),
),
padding: EdgeInsets.only(left: 16.w, right: 13.w),
child: Row(
children: [
picked.isEmpty ? pickedEmpty() : pickedNotEmpty(),
const Spacer(),
const Icon(
Icons.arrow_drop_down,
color: style.bdbdbd,
),
],
),
),
);
}
Widget pickedEmpty() {
return Text(
"Možete obeležiti više aktivnosti",
style: TextStyle(
fontSize: 16.sp,
color: style.bdbdbd,
fontWeight: FontWeight.w400,
),
);
}
Widget pickedNotEmpty() {
List<Widget> list = <Widget>[];
for (var i = 0; i < picked.length; i++) {
list.add(
Padding(
padding: EdgeInsets.only(right: 5.w),
child: Text(
picked[i],
style: TextStyle(
fontSize: 16.sp,
color: style.bdbdbd,
fontWeight: FontWeight.w400,
),
),
),
);
}
return Row(children: list);
}
Widget dropdownExpanded() {
return Container(
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: style.purpleMain),
borderRadius: BorderRadius.circular(8),
),
child: Column(
children: [
GestureDetector(
onTap: () {
setState(() {
isPressed = !isPressed;
});
overlayEntry?.remove();
},
child: Container(
width: double.infinity,
height: 50.h,
padding: EdgeInsets.only(left: 16.w, right: 13.w),
child: Row(
children: [
picked.isEmpty ? pickedEmpty() : pickedNotEmpty(),
const Spacer(),
const Icon(
Icons.arrow_drop_up,
color: style.bdbdbd,
),
],
),
),
),
const Divider(
height: 0,
thickness: 1,
color: style.e8e8e8,
indent: 17,
endIndent: 17,
),
Column(
children: [
for (int i in ints) buildRows(i),
],
),
],
),
);
}
Here are results
This is what I want to accomplish
So I just want to move down this expanded dropdown and how to update these booles in the overlay if I don't use overlay it's working as it should but I need to open that dropdown on the top of another content. Thanks for the help.
Use smart_select it is fully customizable and you can achieve the design you want easily using this library.
Updated Answer
Regarding the UI, it is like an Expansions Tile Widget in flutter. You can implement that dropdown with expansions tile and pass list of items in children,
for expand, collapse tile after select each item, you can create a global key and control that in UI.
final GlobalKey<AppExpansionTileState> expansionTile = new GlobalKey();
collapse → expansionTile.currentState.collapse();
ExpansionTile(
title: Text(
"Možete obeležiti više aktivnosti",
style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.w500),
),
children: <Widget>[
// put items here
],
),
smaple :
Widget customDropDown() => Container(
// color: Colors.white,
padding: const EdgeInsets.all(10),
child: ListTileTheme(
dense: true,
child: ExpansionTile(
title: const Text(
"Možete obeležiti više aktivnosti",
style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.w500),
),
children: <Widget>[
Container(
width: double.infinity,
decoration: const BoxDecoration(
color: Colors.white,
borderRadius:
BorderRadius.vertical(bottom: Radius.circular(20))),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: const [
ListTile(
leading: Icon(Icons.ac_unit),
title: Text("something"),
),
ListTile(
leading: Icon(Icons.ac_unit),
title: Text("something"),
),
ListTile(
leading: Icon(Icons.ac_unit),
title: Text("something"),
),
ListTile(
leading: Icon(Icons.ac_unit),
title: Text("something"),
)
],
),
),
)
],
),
),
);
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: SafeArea(
child: Stack(
children: [pageDesign(), customDropDown()],
),
),
),
);
}
fakeWidget(color) => Container(
height: 100,
width: double.infinity,
color: color,
child: const Center(
child: Text("widget1"),
),
);
Widget pageDesign() => Column(
children: [
/* you should control this size in diffrent orientation and for big size
device to handle responsive
*/
const SizedBox(
height: 80,
),
fakeWidget(
Colors.green,
),
fakeWidget(
Colors.yellow,
),
fakeWidget(
Colors.orange,
),
fakeWidget(
Colors.blue,
),
],
);

Navigate using bottom app bar tabs - flutter

I am using bottom app bar for bottomnavigation in flutter. when tapped on one of the tab in the bottom app bar, i would still want the bottom app bar and app bar to remain as it is in it's fixed position but only the body content changes based on what is tapped.
I have tried to use push() method but it gives me a new page instead with a back button.
Navigation_tabs.dart:
import 'package:flutter/material.dart';
class NavigationTabs extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () {},
),
appBar: AppBar(
title: Text('Dashboard'),
),
bottomNavigationBar: BottomAppBar(
shape: CircularNotchedRectangle(),
notchMargin: 4.0,
child: new Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(
Icons.home,
color: Colors.cyan[700],
),
onPressed: () {},
),
new Container(
padding: EdgeInsets.only(left: 20),
child: IconButton(
icon: Icon(
Icons.list,
color: Colors.cyan[700],
),
onPressed: () => Navigator.pushNamed(context, '/login'),
)),
new Container(
padding: EdgeInsets.only(left: 120),
child: IconButton(
icon: Icon(
Icons.explore,
color: Colors.cyan[700],
),
onPressed: () {},
)),
new Container(
height: 22.0,
child: new RawMaterialButton(
onPressed: () {},
child: new Icon(
Icons.person,
color: Colors.white,
size: 20.0,
),
shape: new CircleBorder(),
elevation: 1.0,
fillColor: Colors.cyan[700],
))
],
),
));
}
}
I want to be able to only make the page content change without a back button instead of going to a completely new page when one of the tabs is pressed.
You can use a BottomNavigationBarItem instead of creating buttons and use the ontap of the bottomNavigationBar.
class _MyHomePageState extends State<MyHomePage> {
int _index = 0;
final List<Widget> _children = [
Center(child: Text("First Page"),),
Center(child: Text("Second Page"),),
Center(child: Text("Third Page"),)
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Bottom Navigation"),
),
body: Center(
child: (_children[_index ]),
),
bottomNavigationBar: BottomNavigationBar(
onTap: onTabTapped,
currentIndex: _currentIndex,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.looks_one),
title: Text('First'),
),
BottomNavigationBarItem(
icon: Icon(Icons.looks_two),
title: Text('Second'),
),
BottomNavigationBarItem(
icon: Icon(Icons.looks_3),
title: Text('Third'),
)
],
),
);
}
void onTabTapped(int index) {
setState(() {
_index = index;
});
}
}
For more detailed explanation:
Flutter documentation

is it Possible to Implement a Dismissible widget for a button inside a SliverList in flutter

so lets say I have built a sliverlist that looks like this.
return new Container(
child: new CustomScrollView(
scrollDirection: Axis.vertical,
shrinkWrap: false,
slivers: <Widget>[
new SliverPadding(
padding: const EdgeInsets.symmetric(vertical: 2.0),
sliver: new SliverList(
delegate: new SliverChildBuilderDelegate(
(BuildContext context, int index) {
ModelClass class= _List[index];
return new Dismissible(
key: new ObjectKey(_List[index]),
child: ModelCard(class),
onDismissed: (DismissDirection direction) {
setState(() {
_List.removeAt(index);
direction == DismissDirection.endToStart;
});
},
background: new Container(
color: const Color.fromRGBO(183, 28, 28, 0.8),
child: new Center(
child: new Text(
"Item Removed",
style: new TextStyle(color: Colors.white),
),
)),
);
// return new ModelCard(class);
}, childCount: _List.length),
),
),
],
));
and now i have a stateless widget called ModelCard to populate the list like this one
new Container(
padding: EdgeInsets.fromLTRB(80.0, 10.0, 0.0, 0.0),
child: new Text(
"${class.listDescription}",
style: new TextStyle(),
),
),
now I want to have an Icon button to dismiss an item so i added it inside the card
new Container(
padding: EdgeInsets.fromLTRB(350.0, 20.0, 0.0, 0.0),
child: new IconButton(
icon: new Icon(Icons.delete), onPressed: () {}),
),
How would you implement the dismissible widget inside an icon button that dismiss an Item in a list when pressed in flutter?
Ok , there is already a package which do what you need.
https://pub.dartlang.org/packages/flutter_slidable
A Flutter implementation of slidable list item with directional slide
actions that can be dismissed.
Usage:
new Slidable(
delegate: new SlidableScrollDelegate(),
actionExtentRatio: 0.25,
child: new Container(
color: Colors.white,
child: new ListTile(
leading: new CircleAvatar(
backgroundColor: Colors.indigoAccent,
child: new Text('$3'),
foregroundColor: Colors.white,
),
title: new Text('Tile n°$3'),
subtitle: new Text('SlidableDrawerDelegate'),
),
),
actions: <Widget>[
new IconSlideAction(
caption: 'Archive',
color: Colors.blue,
icon: Icons.archive,
onTap: () => _showSnackBar('Archive'),
),
new IconSlideAction(
caption: 'Share',
color: Colors.indigo,
icon: Icons.share,
onTap: () => _showSnackBar('Share'),
),
],
);

Swipe List Item for more options (Flutter)

Somedays ago I decided to choose an Ui for an app from Pinterest to practice building apps with Flutter but I'm stuck with the Slider which shows an "more" and "delete" button on horizontal drag. Picture on the right.
I don't have enough knowledge to use Gestures combined with Animations to create something like this in flutter. Thats why I hope that someone of you can make an example for everyone like me that we can understand how to implement something like this in a ListView.builder.
(Source)
An gif example from the macOS mail App:
I created a package for doing this kind of layout: flutter_slidable (Thanks Rémi Rousselet for the based idea)
With this package it's easier to create contextual actions for a list item. For example if you want to create the kind of animation you described:
You will use this code:
new Slidable(
delegate: new SlidableDrawerDelegate(),
actionExtentRatio: 0.25,
child: new Container(
color: Colors.white,
child: new ListTile(
leading: new CircleAvatar(
backgroundColor: Colors.indigoAccent,
child: new Text('$3'),
foregroundColor: Colors.white,
),
title: new Text('Tile n°$3'),
subtitle: new Text('SlidableDrawerDelegate'),
),
),
actions: <Widget>[
new IconSlideAction(
caption: 'Archive',
color: Colors.blue,
icon: Icons.archive,
onTap: () => _showSnackBar('Archive'),
),
new IconSlideAction(
caption: 'Share',
color: Colors.indigo,
icon: Icons.share,
onTap: () => _showSnackBar('Share'),
),
],
secondaryActions: <Widget>[
new IconSlideAction(
caption: 'More',
color: Colors.black45,
icon: Icons.more_horiz,
onTap: () => _showSnackBar('More'),
),
new IconSlideAction(
caption: 'Delete',
color: Colors.red,
icon: Icons.delete,
onTap: () => _showSnackBar('Delete'),
),
],
);
There's already a widget for this kind of gesture. It's called Dismissible.
You can find it here. https://docs.flutter.io/flutter/widgets/Dismissible-class.html
EDIT
If you need the exact same transtion, you'd probably have to implement if yourself.
I made a basic example. You'd probably want to tweak the animation a bit, but it's working at least.
class Test extends StatefulWidget {
#override
_TestState createState() => new _TestState();
}
class _TestState extends State<Test> {
double rating = 3.5;
#override
Widget build(BuildContext context) {
return new Scaffold(
body: new ListView(
children: ListTile
.divideTiles(
context: context,
tiles: new List.generate(42, (index) {
return new SlideMenu(
child: new ListTile(
title: new Container(child: new Text("Drag me")),
),
menuItems: <Widget>[
new Container(
child: new IconButton(
icon: new Icon(Icons.delete),
),
),
new Container(
child: new IconButton(
icon: new Icon(Icons.info),
),
),
],
);
}),
)
.toList(),
),
);
}
}
class SlideMenu extends StatefulWidget {
final Widget child;
final List<Widget> menuItems;
SlideMenu({this.child, this.menuItems});
#override
_SlideMenuState createState() => new _SlideMenuState();
}
class _SlideMenuState extends State<SlideMenu> with SingleTickerProviderStateMixin {
AnimationController _controller;
#override
initState() {
super.initState();
_controller = new AnimationController(vsync: this, duration: const Duration(milliseconds: 200));
}
#override
dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
final animation = new Tween(
begin: const Offset(0.0, 0.0),
end: const Offset(-0.2, 0.0)
).animate(new CurveTween(curve: Curves.decelerate).animate(_controller));
return new GestureDetector(
onHorizontalDragUpdate: (data) {
// we can access context.size here
setState(() {
_controller.value -= data.primaryDelta / context.size.width;
});
},
onHorizontalDragEnd: (data) {
if (data.primaryVelocity > 2500)
_controller.animateTo(.0); //close menu on fast swipe in the right direction
else if (_controller.value >= .5 || data.primaryVelocity < -2500) // fully open if dragged a lot to left or on fast swipe to left
_controller.animateTo(1.0);
else // close if none of above
_controller.animateTo(.0);
},
child: new Stack(
children: <Widget>[
new SlideTransition(position: animation, child: widget.child),
new Positioned.fill(
child: new LayoutBuilder(
builder: (context, constraint) {
return new AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return new Stack(
children: <Widget>[
new Positioned(
right: .0,
top: .0,
bottom: .0,
width: constraint.maxWidth * animation.value.dx * -1,
child: new Container(
color: Colors.black26,
child: new Row(
children: widget.menuItems.map((child) {
return new Expanded(
child: child,
);
}).toList(),
),
),
),
],
);
},
);
},
),
)
],
),
);
}
}
EDIT
Flutter no longer allows type Animation<FractionalOffset> in SlideTransition animation property. According to this post https://groups.google.com/forum/#!topic/flutter-dev/fmr-C9xK5t4 it should be replaced with AlignmentTween but this also doesn't work. Instead, according to this issue: https://github.com/flutter/flutter/issues/13812 replacing it instead with a raw Tween and directly creating Offset object works instead. Unfortunately, the code is much less clear.
Updated Code with Null Safety: Flutter: 2.x
Firstly you need to add the flutter_slidable package in your project and add below code then Let's enjoy...
Slidable(
actionPane: SlidableDrawerActionPane(),
actionExtentRatio: 0.25,
child: Container(
color: Colors.white,
child: ListTile(
leading: CircleAvatar(
backgroundColor: Colors.indigoAccent,
child: Text('$3'),
foregroundColor: Colors.white,
),
title: Text('Tile n°$3'),
subtitle: Text('SlidableDrawerDelegate'),
),
),
actions: <Widget>[
IconSlideAction(
caption: 'Archive',
color: Colors.blue,
icon: Icons.archive,
onTap: () => _showSnackBar('Archive'),
),
IconSlideAction(
caption: 'Share',
color: Colors.indigo,
icon: Icons.share,
onTap: () => _showSnackBar('Share'),
),
],
secondaryActions: <Widget>[
IconSlideAction(
caption: 'More',
color: Colors.black45,
icon: Icons.more_horiz,
onTap: () => _showSnackBar('More'),
),
IconSlideAction(
caption: 'Delete',
color: Colors.red,
icon: Icons.delete,
onTap: () => _showSnackBar('Delete'),
),
],
);
I have a task that needs the same swipeable menu actions I tried answeres of Romain Rastel and Rémi Rousselet. but I have complex widget tree. the issue with that slideable solutions is they go on other widgets(to left widgets of listview). I found a batter solution here someone wrote a nice article medium and GitHub sample is here.
I look at a lot of articles and answers, and find #Rémi Rousselet answer the best fitted to use without third party libraries.
Just put some improvements to #Rémi's code to make it usable in modern SDK without errors and null safety.
Also I smooth a little bit movement, to make the speed of buttons appeared the same as finger movement.
And I put some comments into the code:
import 'package:flutter/material.dart';
class SlidebleList extends StatefulWidget {
const SlidebleList({Key? key}) : super(key: key);
#override
State<SlidebleList> createState() => _SlidebleListState();
}
class _SlidebleListState extends State<SlidebleList> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: ListTile.divideTiles(
context: context,
tiles: List.generate(42, (index) {
return SlideMenu(
menuItems: <Widget>[
Container(
color: Colors.black12,
child: IconButton(
icon: const Icon(Icons.more_horiz),
onPressed: () {},
),
),
Container(
color: Colors.red,
child: IconButton(
color: Colors.white,
icon: const Icon(Icons.delete),
onPressed: () {},
),
),
],
child: const ListTile(
title: Text("Just drag me"),
),
);
}),
).toList(),
),
);
}
}
class SlideMenu extends StatefulWidget {
final Widget child;
final List<Widget> menuItems;
const SlideMenu({Key? key,
required this.child, required this.menuItems
}) : super(key: key);
#override
State<SlideMenu> createState() => _SlideMenuState();
}
class _SlideMenuState extends State<SlideMenu> with SingleTickerProviderStateMixin {
late AnimationController _controller;
#override
initState() {
super.initState();
_controller = AnimationController(
vsync: this, duration: const Duration(milliseconds: 200));
}
#override
dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
//Here the end field will determine the size of buttons which will appear after sliding
//If you need to appear them at the beginning, you need to change to "+" Offset coordinates (0.2, 0.0)
final animation =
Tween(begin: const Offset(0.0, 0.0),
end: const Offset(-0.2, 0.0))
.animate(CurveTween(curve: Curves.decelerate).animate(_controller));
return GestureDetector(
onHorizontalDragUpdate: (data) {
// we can access context.size here
setState(() {
//Here we set value of Animation controller depending on our finger move in horizontal axis
//If you want to slide to the right, change "-" to "+"
_controller.value -= (data.primaryDelta! / (context.size!.width*0.2));
});
},
onHorizontalDragEnd: (data) {
//To change slide direction, change to data.primaryVelocity! < -1500
if (data.primaryVelocity! > 1500)
_controller.animateTo(.0); //close menu on fast swipe in the right direction
//To change slide direction, change to data.primaryVelocity! > 1500
else if (_controller.value >= .5 || data.primaryVelocity! < -1500)
_controller.animateTo(1.0); // fully open if dragged a lot to left or on fast swipe to left
else // close if none of above
_controller.animateTo(.0);
},
child: LayoutBuilder(builder: (context, constraint) {
return Stack(
children: [
SlideTransition(
position: animation,
child: widget.child,
),
AnimatedBuilder(
animation: _controller,
builder: (context, child) {
//To change slide direction to right, replace the right parameter with left:
return Positioned(
right: .0,
top: .0,
bottom: .0,
width: constraint.maxWidth * animation.value.dx * -1,
child: Row(
children: widget.menuItems.map((child) {
return Expanded(
child: child,
);
}).toList(),
),
);
})
],
);
})
);
}
}
i had the same problem and and as the accepted answer suggests, i used flutter_slidable
but i needed a custom look for the actions and also i wanted them to be vertically aligned not horizontal.
i noticed that actionPane() can take a list of widgets as children not only
SlidableAction.
so i was able to make my custom actions,and wanted to share the code and results with you here.
this is the layout
this is the code i used :
ListView.builder(
itemBuilder: (context, index) {
return Slidable(
startActionPane: ActionPane(
motion: const ScrollMotion(),
extentRatio: 0.25,
// A pane can dismiss the Slidable.
// All actions are defined in the children parameter.
children: [
Expanded(
flex: 1,
child: Card(
margin: const EdgeInsets.symmetric(
horizontal: 8, vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
child: Column(
children: [
Expanded(
child: InkWell(
child: Container(
width: double.infinity,
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Icon(Icons.edit,
color:
Colors.deepPurple),
Text(
LocalizationKeys.edit.tr,
style: TextStyle(
color:
Colors.deepPurple,
fontSize: 16),
),
],
),
),
onTap: () {},
),
),
Container(
height: 1,
color: Colors.deepPurple,
),
Expanded(
child: InkWell(
child: Container(
width: double.infinity,
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Icon(Icons.delete,
color: Colors.red),
Text(
LocalizationKeys
.app_delete.tr,
style: TextStyle(
color: Colors.red,
fontSize: 16),
),
],
),
),
onTap: () {},
),
),
],
),
),
),
]),
child: Card(
margin: EdgeInsets.all(16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
elevation: 0,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(height: 16),
Text(_lecturesViewModel
.lectures.value[index].centerName),
SizedBox(height: 16),
Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(_lecturesViewModel
.lectures.value[index].classLevel),
Text(_lecturesViewModel
.lectures.value[index].material),
],
),
SizedBox(height: 16),
Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.location_pin),
Text(_lecturesViewModel
.lectures.value[index].city),
Text(_lecturesViewModel
.lectures.value[index].area),
],
),
SizedBox(height: 16),
Row(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: [
Column(
children: [
Icon(Icons.calendar_today),
Text(_lecturesViewModel
.lectures.value[index].day),
],
),
Container(
height: 1,
width: 60,
color: Colors.black,
),
Column(
children: [
Icon(Icons.punch_clock),
Text(_lecturesViewModel
.lectures.value[index].time),
],
),
Container(
height: 1,
width: 60,
color: Colors.black,
),
Column(
children: [
Icon(Icons.money),
Text(
"${_lecturesViewModel.lectures.value[index].price.toString()}ج "),
],
)
]),
SizedBox(height: 16),
]),
),
);
},
itemCount: _lecturesViewModel.lectures.length,
physics: BouncingScrollPhysics(),
)

Categories

Resources