Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Custom Widget - How to obtain a value from

Tags:

flutter

widget

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'),
    );
  }
}
like image 733
Brian Oh Avatar asked Mar 04 '23 01:03

Brian Oh


1 Answers

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.

like image 139
Hosar Avatar answered Apr 03 '23 04:04

Hosar