This is a simple example of the problem that I have. Given the following example, how can I obtain the value of "counter" from outside the Class?
class Counter extends StatefulWidget {
@override
_CounterState createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int counter = 0;
void increaseCount() {
setState(() => this.counter++);
print("New count = $counter");
}
Widget build(context) {
return new RaisedButton(
onPressed: increaseCount,
child: new Text('Tap To Add'),
);
}
}
In Flutter what you normally do is to pass a callback function, in that function you can pass the value you need, e.g.
class Counter extends StatefulWidget {
// you can use a callback function
final ValueSetter<int> callback;
Counter({this.callback});
@override
_CounterState createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int counter = 0;
void increaseCount() {
setState(() => this.counter++);
print("New count = $counter");
// Here you can pass the value
widget.callback(this.counter);
}
Widget build(context) {
return new RaisedButton(
onPressed: increaseCount,
child: new Text('Tap To Add'),
);
}
}
And when calling your widget, you do as follow:
Counter(callback: (counter){
// Here you can take some actions on counter
});
This is the most simple way I know, or you can use some other patterns like bloc or something else.
Hope this help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With