OnPressed Parameter issue with Text - flutter

Container(
height: 50.0,
margin: EdgeInsets.symmetric(horizontal: 60),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
color: Color.fromRGBO(49, 39, 79, 1),
),
child: Center(
child: Text(
"Login", style: TextStyle(color: Colors.white),),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondPage()),
);
}
),
),
Hi, could someone take a look at this code? I am having issues implementing switching pages in Flutter. The parameter for onPressed is not defined. This would mean that I need to put the function on a button or not? Can't I have the function be on the container along with the text?

You are using the property onPressed inside the widget Text. The class Text does not have an onPressed property, you can check here:
https://api.flutter.dev/flutter/widgets/Text-class.html
If you want to use the onPressed property then you can use the widget RaisedButton for example.
https://api.flutter.dev/flutter/material/RaisedButton-class.html

We don't apply onPressed on Text.
It is available for Buttons such as Raised buttons.
Refer : Raised button

You can wrap your Text widget in a GestureDetector widget like this:
Container(
height: 50.0,
margin: EdgeInsets.symmetric(horizontal: 60),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
color: Color.fromRGBO(49, 39, 79, 1),
),
child: Center(
child: GestureDetector(
child: Text(
"Login",
style: TextStyle(color: Colors.white),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondPage()),
);
},
),
),
),

Related

Ink ripple effect when using GestureDetector

I need to use a GestureDetector because it can detect many more types of user interactions than InkWell, but unlike InkWell it doesn't provide any visual response when a user taps or long presses on it.
Is it possible to add a ripple effect for tap/long press while still handling user interactions in the GestureDetector?
Just use this plugin
touch_ripple_effect: ^2.2.4
Touch ripple effect
TouchRippleEffect(
borderRadius: _helloRadius,
rippleColor: Colors.white60,
onTap: (){
print("Anand !");
},
child: Container(
width: 110,
height: 50,
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.pink, borderRadius: _helloRadius),
child: IconButton(
iconSize: 24.0,
icon: Icon(Icons.search,color: Colors.white, size: 36,),
onPressed: null
),)
),
Touch Feedback effect
TouchFeedback(
onTap: (){
print(" I am Aditya");
},
rippleColor: Colors.blue[200],
child: Container(
width: 120,
height: 40,
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.yellow, borderRadius: BorderRadius.circular(5),),
child: Text(
"Hit me !",
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)
)
),
)
if you want a quick hack, check this:
class Test extends StatelessWidget {
const Test({
Key? key,
this.onTap,
}) : super(key: key);
final void Function()? onTap;
#override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
return Scaffold(
body: GestureDetector(
onTap: onTap,
child: SizedBox(
width: width * 0.2,
height: 70,
child: Card(
color: Colors.red,
child: InkWell(
onTap: () {},
),
),
),
),
);
}
}
Try the following code:
InkWell(
onLongPress: () {
// Do what you want to do
},
child: child,
),

Passing function as parameter to a widget

I have a button that calls a widget to open a custom dialog:
child: GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (context){
return MovMapAlert(
titulo: "yasiguiendo".tr(),
texto: "dejarsiguiendo".tr(),
aceptar: "dejardeseguir".tr(),
cancelar: "cancelar".tr(),
funcion: SeguidoresCrud().dejarDeSeguir(documentIdSeguidores),);
});
},
child: Image.asset('assets/profile/boton_follow_rojo.png'),
)
)
As you may see,I am posting some parameters to the custom dialog widget, including a function that should be executed when the user taps on a dialog button.
Here you have the custom dialog widget:
class MovMapAlert extends StatelessWidget {
final String titulo;
final String texto;
final String aceptar;
final String cancelar;
final Function funcion;
const MovMapAlert({Key key, this.titulo, this.texto, this.aceptar, this.cancelar, this.funcion}) : super(key: key);
#override
Widget build(BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16)
),
elevation: 0,
backgroundColor: Colors.transparent,
child: _buildChild(context),
);
}
_buildChild(BuildContext context) => Container(
height: 350,
decoration: BoxDecoration(
color: Colors.redAccent,
shape: BoxShape.rectangle,
borderRadius: BorderRadius.all(Radius.circular(12))
),
child: Column(
children: <Widget>[
Container(
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Image.asset('assets/images/movmap_transparente1024.png', height: 120, width: 120,),
),
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.rectangle,
borderRadius: BorderRadius.only(topLeft: Radius.circular(12), topRight: Radius.circular(12))
),
),
SizedBox(height: 24,),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(this.titulo, style: TextStyle(fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold),),
),
SizedBox(height: 8,),
Padding(
padding: const EdgeInsets.only(right: 16, left: 16),
child: Text(this.texto, style: TextStyle(fontSize: 18,color: Colors.white), textAlign: TextAlign.center,),
),
SizedBox(height: 24,),
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
FlatButton(onPressed: (){
Navigator.of(context).pop();
}, child: Text(this.cancelar),textColor: Colors.white,),
SizedBox(width: 8,),
RaisedButton(onPressed: (){
return Navigator.of(context).pop(true);
this.funcion();
}, child: Text(this.aceptar), color: Colors.white, textColor: Colors.redAccent,)
],
)
],
),
);
}
My issue is that the line of code that should include the function to be posted to the dialog widget :
funcion: SeguidoresCrud().dejarDeSeguir(documentIdSeguidores),
is marked as warning in the editor, the warning message says: Convert to an if element
I guess I am not doing it well, I mean, what I need is to pass a function as parameter to another widget, if possible...
The problem is that you're calling the function, not passing it
Change to:
funcion: () => SeguidoresCrud().dejarDeSeguir(documentIdSeguidores),
This happens because when you pass the function using (), you're actually calling the function and passing it's return value as an argument not the function itself to be called elsewhere
Pass function with () invoking operator
funcion: (){
SeguidoresCrud().dejarDeSeguir(documentIdSeguidores);
},

Want to Show an AlertDialog when clicking on a Button, on Pressed Method shows an error. ( Undefined name 'context' .)

Hey im New in learning Flutter and Dart. Please help me. :)
I really donĀ“t know what to do I`m a totaly beginner. :/
Now I have pastet my complete code I hope you can see where I defined my Container.
This all is a TabView because I want to train an play with some examples so I tryed out the TabView. In The TabView I packed then all in Containers. If there is a better option, you can tell me of course also. :)
This is my Code:
Future<void> _showAlert(BuildContext context) async {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Accept?'),
content: Text("Do you accept?"),
actions: <Widget>[
FlatButton(onPressed: (){
Navigator.of(context).pop();
},
child: Text('No')
),
FlatButton(onPressed: (){
Navigator.of(context).pop();
},
child: Text('Yes')
),
],
backgroundColor: Colors.deepOrange,
shape: CircleBorder(),
);
}
);
}
class MyApp extends StatelessWidget {
List<Widget> containers = [
Container(
color: Colors.orange,
padding: EdgeInsets.all(20.0),
alignment: Alignment.center,
child: Container(
height: 80,
width: 80,
child: FloatingActionButton(
child: Icon(Icons.check),
tooltip: ('"Hello World"'),
onPressed: () {
print('Hello World');
},
backgroundColor: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(16.0),
),
),
),
),
),
Container(
color: Colors.teal,
alignment: Alignment.center,
child: RaisedButton(
onPressed: () {
print("Raised Button clicked!");
},
child: Text(
"Please click on me!",
style: TextStyle(fontSize: 18),
),
),
),
Container(
color: Colors.deepPurple,
alignment: Alignment.center,
child: RaisedButton(onPressed: () {_showAlert(context);},
color: Colors.deepOrange,
child: Icon(Icons.warning)
),
),
];
The Error says: Undefined name 'context'. (In the onPresssed section at my Button.)
Error shown
Code Snippet 1
Code Snippet 2
What you are missing in your Stateless widget is the build method(Which contains the context), but the issue there is that you can't return a List with the build method because it only returns a Widget. In order to fix this, you should first create a function for your list of widgets, then inside the Stateless widget return the function inside of a widget with a children property, like a Column
Your Widget list function
widgetList(BuildContext context) {
return [
Container(
color: Colors.orange,
padding: EdgeInsets.all(20.0),
alignment: Alignment.center,
child: Container(
height: 80,
width: 80,
child: FloatingActionButton(
child: Icon(Icons.check),
tooltip: ('"Hello World"'),
onPressed: () {
print('Hello World');
},
backgroundColor: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(16.0),
),
),
),
),
),
Container(
color: Colors.teal,
alignment: Alignment.center,
child: RaisedButton(
onPressed: () {
print("Raised Button clicked!");
},
child: Text(
"Please click on me!",
style: TextStyle(fontSize: 18),
),
),
),
Container(
color: Colors.deepPurple,
alignment: Alignment.center,
child: RaisedButton(
onPressed: () {
_showAlert(context);
},
color: Colors.deepOrange,
child: Icon(Icons.warning)),
),
];
}
Your Stateless Widget
class MyApp extends StatelessWidget {
#override Widget build(BuildContext context) {
return Column(
children:
widgetList(context)
);
}
}

How do I dismiss an Alert Dialog in Flutter?

I am using an Alert Dialog for the popups in my app. When the onTap is triggered the popup gets called however when I press the 'Cancel' button the popup does not dismiss and the whole screen behind the popup goes black.
This is my code for the popup.
import 'package:flutter/material.dart';
class FancyAlertDialog {
static showFancyAlertDialog(
BuildContext context,
String title,
String message,
{
bool dismissable = true,
Icon icon,
#required String labelPositiveButton,
#required String labelNegativeButton,
#required VoidCallback onTapPositiveButton,
#required VoidCallback onTapNegativeButton,
}) {
assert(context != null, 'context is null!!!');
assert(title != null, 'title is null!!!');
assert(message != null, 'message is null!!!');
assert(labelPositiveButton != null, 'labelPositiveButton is null');
assert(labelNegativeButton != null, 'labelNegativeButton is null');
assert(onTapPositiveButton != null, 'onTapPositiveButton is null');
assert(onTapNegativeButton != null, 'onTapNegativeButton is null');
return showDialog(
context: context,
barrierDismissible: dismissable,
child: Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(4.0),
),
),
child: Wrap(
children: <Widget>[
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(4.0),
topRight: Radius.circular(4.0),
),
color:Colors.red,
),
padding: EdgeInsets.symmetric(vertical: 5.0),
child: Stack(
children: <Widget>[
Align(
child: icon ?? Container(height:0),
alignment: Alignment.topRight,
)
],
),
),
Padding(
padding: EdgeInsets.only(
left: 16.0,
top: 2.0,
right: 16.0,
bottom: 8.0,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Center(
child: Text(
title,
style: Theme.of(context).textTheme.subtitle,
),
),
SizedBox(height: 8.0),
Text(
message,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.caption,
),
SizedBox(height: 16.0),
Row(
children: <Widget>[
Expanded(
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(16.0),
),
),
color: Colors.grey,
child: Text(
labelNegativeButton.toUpperCase(),
style: TextStyle(
color: Colors.white,
),
),
onPressed: onTapNegativeButton,
),
),
SizedBox(width: 16.0),
Expanded(
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(16.0),
),
),
color: Colors.red,
child: Text(
labelPositiveButton.toUpperCase(),
style: TextStyle(
color: Colors.white,
),
),
onPressed: onTapPositiveButton,
),
),
],
)
],
),
),
],
),
),
);
}
}
And this is how I've called the popup.
FancyAlertDialog.showFancyAlertDialog(
context,
'Info Fancy Alert Dialog Box',
'This is a info alert dialog box. This plugin is used to help you easily create fancy dialog',
icon: Icon(
Icons.clear,
color: Colors.black,
),
labelPositiveButton: 'OKAY',
onTapPositiveButton: () {
Navigator.pop(context);
print('tap positive button');
},
labelNegativeButton: 'Cancel',
onTapNegativeButton: () {
Navigator.pop(context);
print('tap negative button');
},
);
This is what my screen looks like when I press the cancel button:
Try this inside your onTap():
Navigator.of(context, rootNavigator: true).pop();
I assume you are using the wrong context object when calling Navigator.pop(context).
At that point the Navigator isn't aware of the dialog yet.
First, provide a new BuildContext within showDialog. There are two ways to do that:
Create a new widget for the child parameter (now Dialog) in the showDialog function.
Wrap the child (Dialog) with a Builder that provides a new BuildContext
Then you should get that new context to the Navigator.pop(context) call. Again, there are two ways to do that:
Pop from within the dialog itself
Pass the context object along as a parameter to the onTapPositiveButton and onTapNegativeButton
More info on the Builder can be found here as well: https://www.youtube.com/watch?v=xXNOkIuSYuA
Try to use this
onTap: () => Navigator.of(context).pop(false),

change color of the Flutter's FlatButton onPressed

I want to change the color and text of the button when i click on it. But it doesnt change. I change my variable in setState and with the ternary operator set the text and color.
I hope you can help guys.
Container(
padding: EdgeInsets.symmetric(horizontal: 15,vertical: 15),
alignment: Alignment.bottomCenter,
child: SizedBox(
width: double.infinity, //Full width
height: 40,
child: FlatButton(
child: Text( stopSelling ? "Dejar de vender" : "Empezar a vender",style: TextStyle(fontSize: 20,fontWeight: FontWeight.w300),),
onPressed: () {
setState(() {
stopSelling = !stopSelling;
});
},
textColor: Colors.white,
color: stopSelling?Colors.red:Colors.green,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
)
),
),
Your code is perfect but i don't know where you declare your stopSelling variable but i am pretty sure you have declared stopSelling inside the build() method so then you have to declare stopSelling variable outside of the build() method and inside of the class(statefull or stateless).
And It's flutter life cycle rules that when setState() is called then at that time build() method called automatically and it will effect your variable as well as before.
try this....
Container(
padding: EdgeInsets.symmetric(horizontal: 15,vertical: 15),
alignment: Alignment.bottomCenter,
child: SizedBox(
width: double.infinity, //Full width
height: 40,
child: stopSelling? FlatButton(
child: Text( stopSelling ? "Dejar de vender" : "Empezar a vender",style: TextStyle(fontSize: 20,fontWeight: FontWeight.w300),),
onPressed: () {
setState(() {
stopSelling = !stopSelling;
});
},
textColor: Colors.white,
color: Colors.red,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
):FlatButton(
child: Text( stopSelling ? "Dejar de vender" : "Empezar a vender",style: TextStyle(fontSize: 20,fontWeight: FontWeight.w300),),
onPressed: () {
setState(() {
stopSelling = !stopSelling;
});
},
textColor: Colors.white,
color: Colors.green,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
),
),
)