Ad

Flutter ElevatedButton OnPressed Functions Avoid Using Unnecessary Statements

- 1 answer

I have a Flutter stateful widget inside a Stepper widget, and it looks like this: enter image description here

The first step of the stepper widget has another widget as its content, and that widget is a stateful widget as below:

import 'package:flutter/material.dart';

class ConductorStart extends StatefulWidget {
  const ConductorStart({
    Key? key,
    required this.continued,
  }) : super(key: key);

  final VoidCallback continued;

  @override
  ConductorStartState createState() => ConductorStartState();
}

class ConductorStartState extends State<ConductorStart> {
  int _currentStep = 0;
  bool _pressedButton = false;

  void tapped() {
    setState(() => _pressedButton = true);
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        if (!_pressedButton)
          ElevatedButton(
            onPressed: () {
              tapped;
              widget.continued;
            },
            child: const Text('Continue'),
          )
        else
          const SizedBox.shrink(),
      ],
    );
  }
}

The ElevatedButton has two functions when called: tapped, and widget.continued. tapped should make the button disappear. and widget.continued is a function from the parent widget that is supposed to make the parent widget to continue to step 2 when clicked. Currently the two functions have a warning of Avoid using unnecessary statements, and they do not get executed properly. When I click the continue button. Nothing happens. What did I do wrong here?

Ad

Answer

I'll totally go with Pat9RB. Just posting it here as an answer for others to quickly find the relevant issue.

Adding just definitions helps for adding a callback parameter in the constructor. For Eg.: onPressed: myOnPressed; where, onPressed needs a VoidCallback, and myOnPressed is a VoidCallback argument.

But, you need to call the function in order to execute it from any other function body. Either call using .call() method, like, tapped!.call(); or append with callback syntax (), like, tapped();

Ad
source: stackoverflow.com
Ad