Home > Net >  Widget SwitchListTile's switch didn't work properly when it's using the widget builde
Widget SwitchListTile's switch didn't work properly when it's using the widget builde

Time:06-23

I am making the Meal shop app which has many types of meals like vegan, vegetarian, etc as boolean var. A page filters out which type of meal the user has to see. So, I am using the SwitchListTile widget the change its bool value. for that, I make the widget builder method but here switch button didn't work. Here is the code.

import 'package:flutter/material.dart';

class FilterPage extends StatefulWidget {
    static const route = '/filter-page';

@override
State<FilterPage> createState() => _FilterPageState();
}

class _FilterPageState extends State<FilterPage> {
var _gluttenFree = false;
var _lectosFree = false;
var _vegan = false;
var _vegitarian = false;

Widget _buildSwitch(
  String title, String descreption, var curValue, Function updateValue) {
return SwitchListTile(
  value: curValue,
  onChanged: (_) => updateValue(),
  title: Text(title),
  subtitle: Text(description),
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text('Filter settings'),
  ),
  drawer: DrawerWidget(),
  body: Column(
    children: [
      Text(
        'Adjust your meal selection',
      ),
      Expanded(
        child: ListView(
          children: [
            _buildSwitch(
              'Gluteen-Free',
              'It is include Gluteen-free meals',
              _gluttenFree,
              (newValue) {
                setState(() {
                  _gluttenFree = newValue;
                });
              },
            ),
          ],
        ),
      )
    ],
    ),
   );
 }
 }

CodePudding user response:

onChanged provides a bool on callback, and it is the selection value of SwitchListTile.

It will be like.

  Widget _buildSwitch(String title, String descreption, bool curValue,
      Function(bool) updateValue) {
    return SwitchListTile(
      value: curValue,
      onChanged: (value) => updateValue(value),
      title: Text(title),
      subtitle: Text(description),
    );
  }
  • Related