how to change property with onPressed in flutter - flutter

I am working on a flutter app and I wanted to change the color property(for each widget) to red when the user clicks on red and to green when the user clicks on the green. So any help?
this is the code of the widgets of the first page
cardItem(BuildContext context, int index){
return Padding(
padding: const EdgeInsets.all(5.0),
child: GestureDetector(
onTap: ()
{
SecondPage.name = "Question ${index +1}";
SecondPage.index = index;
Navigator.push(context, MaterialPageRoute(builder:
(context) => SecondPage()));
},
child: Card(
color: Colors.white,
child: ListTile(
title: Text('Question ${index +1 }'),
subtitle: Text('Yes or No'),
)
)
)
);
}
}
this is the code of the yes or no page
class _SecondPageState extends State<SecondPage> {
#override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
title: Text(SecondPage.name),
),
body: Center(
child:
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.only(right: 3),
child: FlatButton(
padding: EdgeInsets.all(15),
color: Colors.red,
child: Text('No', style: TextStyle(color: Colors.black),),
onPressed: () {
},
),
),
Padding(
padding: EdgeInsets.only(left: 3),
child: FlatButton(
padding: EdgeInsets.all(15),
color: Colors.green,
child: Text('Yes', style: TextStyle(color: Colors.black),),
onPressed: () {
},
),
),
],
),
)
);
}

Define a color variable Color color; inside your state and then give this color to all of your widget like button or whatever you have, And when user clicks on red inside the onPressed of your red button.
color =Colors.red;
setState(() { });
similarly, you can do this inside your green color button.

1). First declare a global variable like this,
var btnColor = Colors.green;
2). Now use this variable inside your widget like this,
color: btnColor,
3). Now use setState on button pressed to change the value of the Color
onPressed: () {
setState(() {
btnColor = Colors.red;
});
},
The value of color will change. This is called Stage-management you can
learn more about that

Related

Fluttere, the last page I closed appears instantly when I open a new page

When I switch between pages in the drawer, the previous page appears for 1 second, then it closes and the page I want appears.
https://youtube.com/shorts/YS5P2aQLBAM?feature=share
#override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
children: [
//Drawer Header
//Drawer Body
Container(
padding: const EdgeInsets.only(left: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
drawerItem(context, () {
Get.to(() => ProfileScreen());
}, "Hesabım", Icons.person),
drawerItem(context, () {
Get.to(() => MyAdress());
}, "Adreslerim", Icons.location_on_sharp),
],
),
),
],
),
);
}
GestureDetector drawerItem(
BuildContext context, VoidCallback onTap, String? a, IconData icon) {
return GestureDetector(
onTap: onTap,
child: ListTile(
leading: Icon(icon, color: Colors.black54),
title: Text(
a.toString(),
style: TextStyle(color: Colors.black54),
),
),
);
}
}
Try the below thing:
On the tap of drawerItem first, close the Drawer by Navigator.pop(context); than move to the next screen.

Passing variables from Tab to DefaultTabController - Flutter

I have a DefaultTabController with two pages nested in a scaffold. In my scaffold's App Bar is a save button and I want this button to return a value to a previous page, based on a variable that is calculated in one of the tabs. How do I get this value?
Here is my DefaultTabController
DefaultTabController(
initialIndex: index,
length: 2,
child: Scaffold(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
appBar: AppBar(
elevation: 0,
backgroundColor: fumigruen_accent,
leading: CloseButton(
color: Colors.black,
onPressed: () {
Navigator.of(context).pop();
},
),
actions: buildEditingActions(),
),
body: Column(children: [
tabBar(),
Expanded(
child: TabBarView(children: [
//1st Tab
GewichtsrechnerEinfach(),
//2nd Tab
Column()
]),
)
]),
));}
And here is the save-Button I want to use to pass a varaible to the previous screen
List<Widget> buildEditingActions() => [
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: fumigruen_accent,
elevation: 0,
foregroundColor: Colors.black,
),
onPressed: () {
Navigator.of(context).pop(gewicht);
},
icon: Icon(Icons.save),
label: Text("Speichern"))
];
The tabbar Code
Widget tabBar() => TabBar(
labelColor: Theme.of(context).primaryColor,
indicatorColor: Theme.of(context).primaryColor,
labelStyle: TextStyle(fontWeight: FontWeight.bold),
tabs: [
Tab(
child: Row(mainAxisSize: MainAxisSize.min, children: [
Icon(
Icons.assessment_outlined,
),
SizedBox(
width: 5,
),
Text("Einfach")
]),
),
Tab(
child: Row(mainAxisSize: MainAxisSize.min, children: [
Icon(
Icons.addchart,
),
SizedBox(
width: 5,
),
Text("Fortgeschritten")
]),
),
]);
and an extract of the GewichtsrechnerEinfach():
class _GewichtsrechnerEinfachState extends State<GewichtsrechnerEinfach> {
final _formKey = GlobalKey<FormState>();
num koerperlaenge = 0;
num brustumfang = 0;
var _koerperlaengeControler = TextEditingController();
var _brustumfangControler = TextEditingController();
num gewicht = 0;
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//{two textinput fields setting the variables koerperlaenge and brustumfang are here}
Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.8,
decoration: ThemeHelper().buttonBoxDecoration(context),
child: ElevatedButton(
style: ThemeHelper().buttonStyle(),
child: Padding(
padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
child: Text(
"berechnen".toUpperCase(),
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
onPressed: () async {
if (_formKey.currentState!.validate()) {
setState(() {
gewicht = Gewichtskalkulator().einfach(
brustumfang.toDouble(),
koerperlaenge.toDouble());
});
}
}),
),
),
],
),
),
),
);
}
The variable "gewicht" is calculated and changed in the first tab "GewichtsrechnerEinfach". So how do I get the changed variable to this main screen so that I can use it while saving?
Thanks a lot :)
As I found out by chatting in comments section, you are changing a value in a Page and you want to use it in another pages or screen, this is why you should use StateManagement something like Provider.
As you said you need to change the gewicht variable and use it where ever you want.
step 1) please add provider: ^6.0.5 (or any version that is compatible) in your pubspec.yaml and call flutter pub get.
step 2) now you should create a provider class to make all the variables that you want to use everywhere, alive. please create a dart file named:
gewichtsrechner_einfach_provider.dart
step 3) now you should put these codes in you provider class:
import 'package:flutter/material.dart';
class GewichtsrechnerEinfachProvider extends ChangeNotifier{
num _gewicht = 0;
num get gewicht => _gewicht;
void setGewicht(num newGewicht){
_gewicht = newGewicht;
notifyListeners();
}
}
as you see _gewicht is private and you can use it alive entire your project.
step 4) you should add the provider to main.dart:
MultiProvider(
providers: [
// you are adding your provider
ListenableProvider.value(value: GewichtsrechnerEinfachProvider()),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: ...........
),
);
step 5) now you should use its setter and getter of gewicht:
as you see in _GewichtsrechnerEinfachState you are setting the value and should do this by using Consumer:
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: SingleChildScrollView(
child: Consumer<GewichtsrechnerEinfachProvider>(//note this
builder: (context, gewichtsrechnerEinfachProvider ,child) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//{two textinput fields setting the variables koerperlaenge and brustumfang are here}
Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.8,
decoration: ThemeHelper().buttonBoxDecoration(context),
child: ElevatedButton(
style: ThemeHelper().buttonStyle(),
child: Padding(
padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
child: Text(
"berechnen".toUpperCase(),
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
onPressed: () async {
if (_formKey.currentState!.validate()) {
// and note this
gewichtsrechnerEinfachProvider.setGewicht(
Gewichtskalkulator().einfach(
brustumfang.toDouble(),
koerperlaenge.toDouble())
);
}
}),
),
),
],
),
);
}
),
),
);
}
step 6) now you should use its getter where ever you want:
List<Widget> buildEditingActions() => [
Consumer<GewichtsrechnerEinfachProvider>(
builder: (context, gewichtsrechnerEinfachProvider ,child) {
return ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: fumigruen_accent,
elevation: 0,
foregroundColor: Colors.black,
),
onPressed: () {
// Navigator.of(context).pop(gewicht);
print('here is your result:
${gewichtsrechnerEinfachProvider.gewicht}');
},
icon: Icon(Icons.save),
label: Text("Speichern"));
}
)
];
note that you can use your provider where ever you want even with this code not just consumer:
var gewichtsrechnerEinfachProvider = Provider.of<GewichtsrechnerEinfachProvider>(context,listen: false);
as you see by changing its value the provider notifies to where you are showing it.
Ich hoffe, ich konnte dir helfen ;)
happy coding my friend...

how to put GestureDetector inside Container alert

I wanna put GestureDetector with container alert but it show error. anyone know how to make this code works? Here the code below which i try to put GestureDetector for the alert container.
Without GestureDetector it works fine but i wanna make whole screen touch able to return to other page.
showPopup(BuildContext context) {
// set up the buttons
// ignore: deprecated_member_use
// set up the AlertDialog
GestureDetector(
Container alert = Container(
child: Stack(
children: <Widget>[
if (controllers!.isNotEmpty)
CarouselSlide2(
controllers: controllers!,
),
Padding(
padding: const EdgeInsets.only(top:688.0,left: 90),
child: GestureDetector(
onTap: () async {
isPop = false;
Navigator.pop(context);
_checkTimer();
},
// child: Icon(Icons.arrow_back,color: Colors.white,size: 100,),
child: DefaultTextStyle(
style: TextStyle(color: Colors.white,fontSize: 30),
child: Text("Tap to return",),
)
),
)
],
)));
// show the dialog
showDialog(
barrierDismissible: true,
context: context,
builder: (BuildContext context) {
return WillPopScope(
onWillPop: () async {
const shouldPop = true;
isPop = false;
Navigator.pop(context);
_checkTimer();
return shouldPop;
},
child: alert);
},
);
}
You are using widget in a wrong way, try this:
Widget alert = GestureDetector(
onTap: () {
print("tap");
},
child: Container(
child: Stack(
children: <Widget>[
if (controllers!.isNotEmpty)
CarouselSlide2(
controllers: controllers!,
),
Padding(
padding: const EdgeInsets.only(top: 688.0, left: 90),
child: GestureDetector(
onTap: () async {
isPop = false;
Navigator.pop(context);
_checkTimer();
},
// child: Icon(Icons.arrow_back,color: Colors.white,size: 100,),
child: DefaultTextStyle(
style: TextStyle(color: Colors.white, fontSize: 30),
child: Text(
"Tap to return",
),
)),
)
],
)),
)

Making a speedial without FloatingActionButton

im trying to make my button open up something similar to this: FAB version of what i want
This is what my code looks like:
return Card(
color: Colors.yellow[100],
child: ListTile(
trailing: IconButton(icon: Icon(Icons.more_vert),
onPressed: () {},
),
leading: Text(document['date'] + '\n' + document['time'], textAlign: TextAlign.center,),
subtitle: Text(
'Loctaion: ' + document['location'],
),
title: Text(document['name'],
textAlign: TextAlign.left, style: TextStyle(fontSize: 20.0)),
),
);
}
I want the IconButton to open up something similar to the SpeedDial, to make the user choose between accept, deny, or choose later for the event.
My ListTile with the Icon.more_vert that i want to be able to open a speeddial
You can copy paste run full code below
You can use https://pub.dev/packages/flutter_portal
Basically use Overlay and show circle button
You can change childAnchor and menuAnchor, and circle button size per your request
It's too long to describe all the detail, please see working demo and full code below
code snippet
ListTile(
trailing: IconButton(
icon: Icon(Icons.more_vert),
onPressed: () => setState(() => showMenu = true),
),
...
return ModalEntry(
visible: showMenu,
onClose: () => setState(() => showMenu = false),
childAnchor: Alignment.topRight,
menuAnchor: Alignment.bottomRight,
menu: Menu(
children: [
ClipOval(
child: Material(
color: Colors.blue, // button color
child: InkWell(
splashColor: Colors.red, // inkwell color
onTap: () {
setState(() => showMenu = false);
},
child: SizedBox(width: 40, height: 40, child: Icon(Icons.menu)),
),
),
),
working demo
full code
import 'package:flutter/material.dart';
import 'package:flutter_portal/flutter_portal.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
builder: (_, child) => Portal(child: child),
home: Scaffold(
appBar: AppBar(
title: const Text('Example'),
),
body: Container(
padding: const EdgeInsets.all(10),
alignment: Alignment.centerLeft,
child: ContextualMenuExample(),
),
),
);
}
}
class ContextualMenuExample extends StatefulWidget {
ContextualMenuExample({Key key}) : super(key: key);
#override
_ContextualMenuExampleState createState() => _ContextualMenuExampleState();
}
class _ContextualMenuExampleState extends State<ContextualMenuExample> {
bool showMenu = false;
#override
Widget build(BuildContext context) {
return ModalEntry(
visible: showMenu,
onClose: () => setState(() => showMenu = false),
childAnchor: Alignment.topRight,
menuAnchor: Alignment.bottomRight,
menu: Menu(
children: [
ClipOval(
child: Material(
color: Colors.blue, // button color
child: InkWell(
splashColor: Colors.red, // inkwell color
onTap: () {
setState(() => showMenu = false);
},
child: SizedBox(width: 40, height: 40, child: Icon(Icons.menu)),
),
),
),
ClipOval(
child: Material(
color: Colors.blue, // button color
child: InkWell(
splashColor: Colors.red, // inkwell color
onTap: () {
setState(() => showMenu = false);
},
child: SizedBox(
width: 40, height: 40, child: Icon(Icons.description)),
),
),
),
ClipOval(
child: Material(
color: Colors.blue, // button color
child: InkWell(
splashColor: Colors.red, // inkwell color
onTap: () {
setState(() => showMenu = false);
},
child: SizedBox(
width: 40, height: 40, child: Icon(Icons.settings)),
),
),
)
],
),
child: Container(
child: Card(
color: Colors.yellow[100],
child: ListTile(
trailing: IconButton(
icon: Icon(Icons.more_vert),
onPressed: () => setState(() => showMenu = true),
),
leading: Text(
"date time",
textAlign: TextAlign.center,
),
subtitle: Text(
'Loctaion',
),
title: Text('name',
textAlign: TextAlign.left, style: TextStyle(fontSize: 20.0)),
),
),
),
);
}
}
class Menu extends StatelessWidget {
const Menu({
Key key,
#required this.children,
}) : super(key: key);
final List<Widget> children;
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 10),
child: Card(
elevation: 8,
child: IntrinsicWidth(
child: Column(
mainAxisSize: MainAxisSize.min,
children: children,
),
),
),
);
}
}
class ModalEntry extends StatelessWidget {
const ModalEntry({
Key key,
this.onClose,
this.menu,
this.visible,
this.menuAnchor,
this.childAnchor,
this.child,
}) : super(key: key);
final VoidCallback onClose;
final Widget menu;
final bool visible;
final Widget child;
final Alignment menuAnchor;
final Alignment childAnchor;
#override
Widget build(BuildContext context) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: visible ? onClose : null,
child: PortalEntry(
visible: visible,
portal: menu,
portalAnchor: menuAnchor,
childAnchor: childAnchor,
child: IgnorePointer(
ignoring: visible,
child: child,
),
),
);
}
}

Button that can change container background color/color for flutter

i'm new to flutter and i'm just learning all the basic for flutter. i came across the button widget and on pressed function and i create a simple container which have a button in it like this
here is the container
Container(
child: Padding(
padding: const EdgeInsets.only(top: 25.0, left: 30),
child: Text("Item 1", style: TextStyle(
color: Colors.lightBlueAccent,
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
),
and here is the button
child: FloatingActionButton(
onPressed(){},
child: Text("+", style: TextStyle(
fontSize: 20,
),
),
backgroundColor: Colors.lightBlue,
),
and i want to make the button have a function to change the container background to a certain color, like blue for example. but i cant seem to found the answer on the internet, i guess for me. is there any method which i can apply or code that i didn't know existed?
thanks in advance!!
Declare Default Material Color
MaterialColor _color = Colors.green;
Change above color inside onPressed()
Container(
color: _color,
child: RaisedButton(onPressed: () {
setState(() {
_color = Colors.blue; // This change Container color
});
}),
)
Although you already got a wonderful answer from jitsm555 still Here is full-example, I hope this helps you further.
import 'package:flutter/material.dart';
void main() {
runApp(ColorChange());
}
class ColorChange extends StatefulWidget {
#override
_ColorChangeState createState() => _ColorChangeState();
}
class _ColorChangeState extends State<ColorChange> {
//Initially color is set to yellow which will be changed when button is pressed
Color color = Colors.yellow;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Change Container Color"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
width: 300,
height: 300,
color: color, //value of color which we will change by pressing buttons
),
/* Below Row of Button when pressed will fire up
the setState and the state of our default color variable will
change according to Button which is pressed
*/
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
color: Colors.red,
child: Text("Red"),
onPressed: () {
setState(() {
color = Colors.red;
});
},
),
RaisedButton(
color: Colors.green,
child: Text("Green"),
onPressed: () {
setState(() {
color = Colors.green;
});
},
),
RaisedButton(
color: Colors.blue,
child: Text("Blue"),
onPressed: () {
setState(() {
color = Colors.blue;
});
},
),
],
),
],
),
),
),
);
}
}
Output: