This is my code. I want Change State from one stateful class to another stateful class
here a cart on navigation and I want change from button class
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
int cart = 10;
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text("data"),
actions: <Widget>[
TopCart(),
],
),
body: Container(
child: Center(
child: Buttons(),
),
),
),
);
}
}
class TopCart extends StatefulWidget {
@override
_TopCartState createState() => _TopCartState();
}
class _TopCartState extends State<TopCart> {
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Color(0xffffffff),
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: <Widget>[
Icon(
Icons.card_travel,
color: Colors.blue,
),
Text(
cart.toString(),
style: TextStyle(
color: Colors.blue,
fontSize: 25,
),
)
],
),
);
}
}
class Buttons extends StatefulWidget {
@override
_ButtonsState createState() => _ButtonsState();
}
class _ButtonsState extends State<Buttons> {
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
GestureDetector(
onTap: () {
cart = cart - 1;
print(cart);
},
child: Container(
width: MediaQuery.of(context).size.width / 2 - 24,
height: MediaQuery.of(context).size.width / 2 - 24,
color: Colors.green,
child: Icon(
Icons.add,
color: Colors.white,
),
),
),
GestureDetector(
onTap: () {
cart = cart - 1;
print(cart);
},
child: Container(
width: MediaQuery.of(context).size.width / 2 - 24,
height: MediaQuery.of(context).size.width / 2 - 24,
color: Colors.red,
child: Icon(
Icons.remove,
color: Colors.white,
),
),
),
],
),
);
}
}
Add a function which you want to perform in another class like,
testData(){
print("Test");
}
Now, to use this function to another class like in Buttons class. Pass it as an arguments like,
Container(
child:Buttons(testData);
)
In Buttons Class follow the code like,
// Buttons construtor
Buttons(Function myfunction);
You can use this function now in your second class like on any button tap,
RaisedButton(
child:Text("Save")
onPress:myfunction(),
)
This way you can pass functions as arguments in dart.
User contributions licensed under CC BY-SA 3.0