Home > Software engineering >  Why this function is null?
Why this function is null?

Time:01-13

Im need that function for callback, but it gives a null,

int? _handleIncrement(int? variable) {
    if (variable == null) {
      variable = 0;
    } else if (variable < 5) {
      variable  ;
    } else {
      variable;
    }
  

  void _incrementVariable(int? variable) {
    
        variable = _handleIncrement(variable);
  }
  
  int? val;
  _incrementVariable(val);

I need it in a button

This is the button

class ExpTile extends StatelessWidget {
  final String name;
  final void Function(int?) onIncrement;

  final List<Widget> children;
  final int? variable;

  ExpTile(
      {required this.name,
      this.children = const <Widget>[],
      required this.onIncrement,
      required this.variable,
      key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: ExpansionTile(
          title: ElevatedButton(
            onPressed: () {
              onIncrement(variable);
            },
            child: Row(
              children: [Text(name), Text(variable.toString())],
            ),
          ),
          children: children),
    );
  }

This is the way I call the widget in the father page

ExpTile(
              name: "Defense",
              variable: defense,
              onIncrement: _incrementVariable,
              children: [])

I'm trying different things in dartpad, but I don´t know why the logic doesn't work. always return me the initial value of defense. I'm reading different things about dart functions and callbacks but I dont know where is the problem. Thanks

CodePudding user response:

First, you have to define variable in the parent Widget, if you want to see changes there

class ParentWidget extends StatefulWidget {
  const ParentWidget({super.key, required this.title});
  final String title;

  @override
  State<ParentWidget> createState() => _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  int? variable; //here


  @override
  Widget build(BuildContext context) {
    //your widgets...
              ExpTile(
              name: "Defense",
              variable: variable,
              onIncrement: _incrementVariable,
              children: [])
     //the rest of your widgets...
  }
}

Then you have to define you increment function as a function which changes your variable's value, and redraw the widget.

  void _incrementVariable() {
        setState(() {
          if (variable == null) {
            variable = 0;
          } else if (variable! < 5) {
            variable = variable!   1;
          } 
        });
  }

and then call the function (In the ExpTile widget) this way:

       onPressed: () {
          widget.onIncrement();
        },
  • Related