Flutter: How do you make a card clickable? - material-design

I just have a simple Card like new Card(child: new Text('My cool card')) and I want to be able to click anywhere on it to run some function, except there's no onPressed method for a Card. I could add a button to the bottom, but that's not ideal for this situation.
Anyone know how to make the whole card clickable?

Flutter use composition over properties.
Wrap the desired widget into a clickable one to achieve what you need.
Some clickable widgets : GestureDetector, InkWell, InkResponse.
GestureDetector(
onTap: () => ......,
child: Card(...),
);

Flutter provides the InkWell Widget. by registering a callback you can decide what happens when user clicks on the card (called tap in flutter). InkWell also implements Material Design ripple effect
Card(
child: new InkWell(
onTap: () {
print("tapped");
},
child: Container(
width: 100.0,
height: 100.0,
),
),
),

I think you can also use InkWell apart from GestureDetector just wrap the card inside InkWell() Widget
InkWell(
onTap: (){ print("Card Clicked"); }
child: new Card(),
);

You can use Inkwell and insert splashColor which, at the click of the user, creates the rebound effect with the chosen color, on the card ..
This is mainly used in material design.
return Card(
color: item.completed ? Colors.white70 : Colors.white,
elevation: 8,
child: InkWell(
splashColor: "Insert color when user tap on card",
onTap: () async {
},
),
);

Wrap a card in GestureDetector Widget like a below:
GestureDetector(
onTap: () {
// To do
},
child: Card(
),
),
Another way is as follows:
InkWell(
onTap: () {
// To do
},
child: Card(),
),

In Flutter, InkWell is a material widget that responds to touch action.
InkWell(
child: Card(......),
onTap: () {
print("Click event on Container");
},
);
GestureDetector is a widget that detects the gestures.
GestureDetector(
onTap: () {
print("Click event on Container");
},
child: Card(.......),
)
Difference
InkWell is a material widget and it can show you a Ripple Effect whenever a touch was received.
GestureDetector is more general-purpose, not only for touch but also for other gestures.

The most preferred way is to add ListTile as Card child. Not only does ListTile contain the method onTap it also helps you in making Card interesting.
Card(
child: ListTile(
title: Text('Title')
leading: CircleAvatar(
backgroundImage: AssetImage('assets/images/test.jpg'),
),
onTap: () {
print('Card Clicked');
},
),
),

You also can insert a card into a TextButton:
TextButton clickableCard = TextButton(child: card, onPressed: onCardClick, style: [...]);
This brings the advantage, that you get some features for free. For example in Flutter Web, you get a mousover effect and the cursor changes to the hand so that ths user knows, he can click there. Other additional features can be customised using the style.

Do something on tap/click of 'child' in Flutter:-
Code:-your code looks like:
child: Card(------
------------
--------),
Step1:- Put your mouse cursor on Card then, press- Alt+Enter(in windows) select wrap with widget.
Step2:- Change your default widget into GestureDetector.
final code:-
child: GestureDetector(
onTap: YourOnClickCode(),
child: Card(------
------------
--------),
),

Most of the answers are brilliant but I just want to share mine for the one who wants to make/show a ripple effect on Tap of card or list tile.
Card(
child: TextButton(
onPressed: ()=> ...,
child: ListTile(
title: Text('title'),
),
),
);

Related

How do I add both onPressed and onLongPress to a Flutter Center Widget inside a Row?

I am trying in vain to add onLongPress to an image button along with onPressed. I get error: The named parameter 'onDoubleTap' isn't defined.
I have multiple rows of 2 horizontal image buttons using rows and expanded. Everything works except onLongPress (or onDoubleTap). What am I doing wrong, do I have to rebuild the entire code in a different format, or am I overcomplicating this?
I also tried to add a new child (error: already defined), GestureDetector, InkWell, with no success.
body: SingleChildScrollView(
child: Container(
child: Column(
children: <Widget>[
Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: FlatButton(
onPressed: () {
setState(() {
launchURL();
});
},
//Trying to add onLongPress , error: "onLongPress not defined
//If I try add a new child it says child already defined
onLongPress: () => _showAlertMessage(context, "message"),
padding: EdgeInsets.all(6.0),
child: Image.asset(
'images/image1.png',
))),
Expanded(
child: FlatButton(
onPressed: () {
setState(() {
launchURL();
});
},
padding: EdgeInsets.all(6.0),
child: Image.asset(
'images/image2.png',
)
)//flat button
),//expanded
])), //row-center
//Repeat above for rows of 2 more image buttons
The code runs with a single onPressed for each button and does not display any errors, but adding any second click event displays errors.
Flatbutton only supports the onPressed callback, not onLongpressed, etc. Suggest you re-look at using gesture detector or other widgets that support long press.
I would try using two containers, each wrapped in a gesture detector widget, as children in the row. Each container having a text and/or image content. You can then pick up onTap, double tap, long press, etc on each container. Not tested this as I am on my phone but should work. They are probably more elegant widgets to use than container.
Thanks for the feedback, really appreciated. I replaced flatButton with Gesture detector inside a column, used onTap instead of onPressed, put image in new Column, added onLongPress. The code runs. When I added the second Expanded I got this error:
E/InputMethodManager( 7133): prepareNavigationBarInfo() rootView is null
I read here that "RootView is the View in which all the other views are placed. It is like the root node in a tree structure which is the parent to all the children.", but I can't see my mistake here. I did a full restart and that error is gone.
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: GestureDetector(
onLongPress: () {
setState(() {
_showAlertMessage(context, "message");
});
},
onTap: () {
setState(() {
_launchUrl;
});
},
child: Container(
padding: EdgeInsets.all(6.0),
child: Image.asset(
'images/image1.png',
)
)),
), //Expanded
Expanded(
child: GestureDetector(
on: () {
setState(() {
_showAlertMessage(context, "message");
});
},
onTap: () {
setState(() {
_launchUrl;
});
},
child: Container(
padding: EdgeInsets.all(6.0),
child: Image.asset(
'images/image2.png',
)
)),
),
])),
NOTE: As version 2 of flutter FlatButton is deprecated. You should use TextButton instead.
I don't know how you are using the GestureDetector but it's the best solution fit for your question and supports different aspects of user press Gestures. So I prepared the sample code below to see how it works.
body: SingleChildScrollView(
child: Container(
child: Column(children: <Widget>[
Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: GestureDetector(
onTap: () => print('onTap'),
onLongPress: () => print('onLongPress'),
onDoubleTap: () => print('onDoubleTap'),
child: Image.network(
'https://lp-cms-production.imgix.net/image_browser/social-beast-GettyRF_136327669.jpg?auto=format&fit=crop&sharp=10&vib=20&ixlib=react-8.6.4&w=850&q=50&dpr=2'),
) //flat button
),
Expanded(
child: GestureDetector(
onTap: () => print('onTap'),
onLongPress: () => print('onLongPress'),
onDoubleTap: () => print('onDoubleTap'),
child: Image.network(
'https://lp-cms-production.imgix.net/image_browser/lions-hunting-500pxRF_7416880.jpg?auto=format&fit=crop&sharp=10&vib=20&ixlib=react-8.6.4&w=850&q=50&dpr=2'),
)
), //expanded
])
), //row-center
]
)
)
)
There are yet so many other gestures for GestureDetector that can be found here.
You can use InkWell widget
child: InkWell(
onLongPress: () {
setState(() {
tip++;
});
},
child: FloatingActionButton(
heroTag: "btn+",
onPressed: () {
setState(() {
tip++;
});
},
backgroundColor: Colors.grey.shade400,
child: Icon(
Icons.add,
color: Colors.black,
),
),
),

Is it possible to disable shadow/overlay on dialog?

I'm wondering if there's a way to disable the shadow/overlay affect a dialog has? Basically so I can get a dialog looking like it does on the right side of this image:
My best attempt at this was to use a stack containing my custom dialog which are then toggled to be displayed or not but then I had trouble being able to scroll each custom dialog's own ListView without it messing up another. I know this goes against the Material Design guidelines but I'm trying to replicate a UI from dribble.com.
Thanks!
Edit:
I've managed to almost achieve this affect by editing the showGeneralDialog method but there's still an elevation shadow:
await showGeneralDialog(
context: context,
pageBuilder: (BuildContext buildContext,
Animation<double> animation,
Animation<double> secondaryAnimation) {
return SafeArea(
child: Builder(builder: (context) {
return AlertDialog(
content: Container(
color: Colors.white,
width: 150.0,
height: 150.0,
child: Center(child: Text("Testing"))));
}),
);
},
barrierDismissible: true,
barrierLabel: MaterialLocalizations.of(context)
.modalBarrierDismissLabel,
barrierColor: null,
transitionDuration:
const Duration(milliseconds: 150));
Edit 2: Just an image to illustrate the change on the above code showing that I've so far been able to disable the dark overlay but there's still elevation on the dialog which I can't seem to get rid of:
Edit 3: I think if I'm able to change the AlertDialog in the showGeneralDialog's Builder then I can get it to work but I'm having trouble putting in something which is Material but doesn't take up the whole screen.
Got it to work! You have to create your own dialog like Widget within the Builder of the showGeneralDialog method along with setting the barrierColor to null:
await showGeneralDialog(
context: context,
pageBuilder: (BuildContext buildContext,
Animation<double> animation,
Animation<double> secondaryAnimation) {
return SafeArea(
child: Builder(builder: (context) {
return Material(
color: Colors.transparent,
child: Align(
alignment: Alignment.center,
child: Container(
height: 200.0,
width: 250.0,
color: Colors.white,
child:
Center(child: Text('Testing')))));
}),
);
},
barrierDismissible: true,
barrierLabel: MaterialLocalizations.of(context)
.modalBarrierDismissLabel,
barrierColor: null,
transitionDuration: const Duration(milliseconds: 150));
Friend, set the parameter "elevation" = 0. It's work.
AlertDialog(
elevation: 0,
),
I have achieved the result using below code. Trick is barrierColor property in showDialog method which I set white color with opacity value zero and barrier shadow is vanished
AlertDialog alert = AlertDialog(
backgroundColor: Colors.transparent,
elevation: 0,
content: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Loader(),
],
),
);
showDialog(
barrierColor: Colors.white.withOpacity(0),
barrierDismissible: false,
context: context,
builder: (BuildContext context) {
return WillPopScope(
onWillPop: (){},
child: alert);
},
);
Just set in showDialog the barrierColor parameter to Colors.transparent.
Example:
showDialog(
context: context,
barrierColor: Colors.transparent, // Here the solution
builder: (context) => myDialog(),
);

Blur background behind dialog flutter? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I want to achieve blur background behind dialog on SimpleDialog class. What I'm looking for is something similar to this, but for flutter.
Github Android project
EDIT:
I already checked this question, but this is about the Dialog, I want to implement it on SimpleDialog.
Just wrap your Dialog inside BackdropFilter
return new BackdropFilter(
filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
child: Dialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0)),
backgroundColor: Color(ColorResources.BLACK_ALPHA_65),
child: _dialogContent(),
)
);
Widget _dialogContent() {}//Your dialog view
I implemented blured background with showGeneralDialog method to make a blur transition as smooth as possible. Here is an example:
showGeneralDialog(
barrierDismissible: true,
barrierLabel: '',
barrierColor: Colors.black38,
transitionDuration: Duration(milliseconds: 500),
pageBuilder: (ctx, anim1, anim2) => AlertDialog(
title: Text('blured background'),
content: Text('background should be blured and little bit darker '),
elevation: 2,
actions: [
FlatButton(
child: Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
),
transitionBuilder: (ctx, anim1, anim2, child) => BackdropFilter(
filter: ImageFilter.blur(sigmaX: 4 * anim1.value, sigmaY: 4 * anim1.value),
child: FadeTransition(
child: child,
opacity: anim1,
),
),
context: context,
);
In flutter, The dimming effect behind the dialog and bottom sheets is done using a class named 'ModalBarrier'. So what you can do is just modify the code where it dims the background.
You can easily search the file in 'IntelliJ' by using the shortcut 'Double shift'
First, you need to
import 'dart:ui' show ImageFilter;
Then in the build method change (Line: 96)
child: color == null ? null : DecoratedBox(
decoration: BoxDecoration(
color: color,
),
),
into
child: color == null ? null : BackdropFilter(
filter: new ImageFilter.blur(sigmaX: 3, sigmaY: 3),
child: Container(color: Color(0x01000000)),
),
You can change the value of 'sigma' as per your usecase.
Screenshot : Blurred Dialog
try implementing this code
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
fit: StackFit.expand,
children: <Widget>[
Image.asset('asset url', fit: BoxFit.cover),
blur(),
],
),
),
],
),
);
}
Widget blur(){
if(
//dialog pops up or is active
){
return BackdropFilter(
filter: ImageFilter.blur(sigmaX:5.0,sigmaY:5.0),
);
}
else{
return Image.asset('asset url', fit: BoxFit.cover);////if dialog not active returns an unfiltered image
}
}

Unwanted action button in flutter appbar

I'm building a screen which has a bottom navigation bar, where I placed an burger action button and a floating button, and an appbar where I want to place my app logo.
Even though i didn't give any action to the appbar, the burger icon still appears at the left of the title.
I would like to only have the title in the appbar.
This is my code:
appBar: new AppBar(
title: new Image.asset('assets/logo/logo-home.png', fit: BoxFit.fitHeight),
actions: null,
backgroundColor: Colors.black,
elevation: 0.0,
),
key: _scaffoldKey,
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
child: ImageIcon(new AssetImage("assets/icons/star.png"), color: Colors.black),
backgroundColor: Colors.white,
onPressed: scan,
),
bottomNavigationBar: BottomAppBar(
color: Color.black,
child: new Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(icon: Icon(Icons.menu), color: Colors.white, onPressed: ()=> _scaffoldKey.currentState.openDrawer(),),
],
),
),
If the scaffold has a drawer and the appbar doesn't contain 'leading' property (or with null value), Appbar will append a menu icon in its actions.
It's mentioned in the documents:
If the leading widget is omitted, but the AppBar is in a Scaffold with a Drawer, then a button will be inserted to open the drawer. Otherwise, if the nearest Navigator has any previous routes, a BackButton is inserted instead. This behavior can be turned off by setting the automaticallyImplyLeading to false. In that case a null leading widget will result in the middle/title widget stretching to start.
The solution is easy, just replace title property with leading in your appbar
appBar: new AppBar(
leading: new Image.asset('assets/logo/logo-home.png', fit: BoxFit.fitHeight),
actions: null,
backgroundColor: Colors.black,
elevation: 0.0,
),

Flutter Align widget rect does not detect the onTap gesture

I have a couple of image buttons laid out as follows :
The layout code is :
new Container(
height: 48.0,
child: new Row(
children: <Widget>[
new GestureDetector(
onTap: cancelTurn,
child: new Align(child: new Image.asset("assets/cancel_button.png"), widthFactor: 1.5),
),
new Expanded(child: new Container()),
new GestureDetector(
onTap: confirmTurn,
child: new Align(child: new Image.asset("assets/confirm_button.png"), widthFactor: 1.5),
),
],
),
)
I am using Align widget to hopefully increase the clickable area of the GestureDetector. However, my clicks only work when I click inside the Image widget rect. If you notice, the bounds/rects for Align and Image are different. Align is extended beyond the Image child by using the widthFactor property (set to 1.5)
Any ideas on why the Align widget might not be detecting the tap gesture in its bounds.
Try passing a hitTestBehavior of HitTestBehavior.opaque to the GestureDetector.
Other tips:
Instead of Align, consider a Padding.
Consider using an IconButton with Icons.close and Icons.check instead of embedding a custom png. You could wrap it in a Material to draw the black circle and it will even clip the ink splash for you automatically.
To get the desired effect, you could replace the GestureDetector elements for InkWell. This will give a feedback to the user (due to the Ink animation) and will be activated when the whole area is pressed.
To do that, your container should look like this:
new Container(
height: 48.0,
child: new Row(
children: <Widget>[
new InkWell(
onTap: cancelTurn,
child: new Align(child: new Image.asset("assets/cancel_button.png"), widthFactor: 1.5),
),
new Expanded(child: new Container()),
new InkWell(
onTap: confirmTurn,
child: new Align(child: new Image.asset("assets/confirm_button.png"), widthFactor: 1.5),
),
],
),
)

Resources