'flutter SwitchListTile Not Change State Switch When Click

flutter SwitchListTile Not Change State Switch When Click

When I use a only switch, it works without a function. but using function does not work

class TestListSwitch extends StatefulWidget {
  @override
  State<TestListSwitch> createState() => _TestListSwitchState();
}

class _TestListSwitchState extends State<TestListSwitch> {
  bool _stateLogin = false;

  Widget _buildSwitchListTile(
    String title,
    String description,
    bool currentValue,
    Function updateValue,
  ) {
    return SwitchListTile(
      title: Text(title),
      value: currentValue,
      subtitle: Text(
        description,
      ),
      onChanged: (value) => updateValue,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(),
        body: SafeArea(
          child: _buildSwitchListTile('Autorize', 'test', _stateLogin, (value) {
            setState(
              () {
                _stateLogin = value;
              },
            );
          }),
        ));
  }
}

Please Help Me...



Solution 1:[1]

Here is working solution:

Widget _buildSwitchListTile(
    String title,
    String description,
    bool currentValue,
    Function(bool) updateValue, // changed from Function updateValue
  ) {
    return SwitchListTile(
      title: Text(title),
      value: currentValue,
      subtitle: Text(
        description,
      ),
      onChanged: updateValue, // changed from (value) => updateValue
    );
  }

Your function was not properly passed and called.

Solution 2:[2]

In the parent widget you should also add SetState() to refresh the build widget function

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ante Bule
Solution 2 PhilNue