Currently I want to use the SwitchListTile Widget divided into 1 separate Widget to reuse many times, but when I click on it, nothing happens.
Here is my code:
class SwitchScreen extends StatefulWidget {
const SwitchScreen({super.key});
@override
State<SwitchScreen> createState() => _SwitchScreenState();
}
class _SwitchScreenState extends State<SwitchScreen> {
bool check = false;
Widget _buildSwitchListTile(String title, String description, bool currentValue) {
return SwitchListTile(
title: Text(title),
value: currentValue,
subtitle: Text(description),
onChanged:(newValue) {setState(() { currentValue = newValue; });},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Filters'),
),
body: Column(
children: [
Container(
padding: const EdgeInsets.all(20),
child: Text(
'select',
),
),
Expanded(
child: ListView(
children: [
_buildSwitchListTile(
'text',
'description',
check,
),
],
),
)
],
),
);
}
}
I tried to fix it and it was successful, by passing a function to my custom Widget like the code below:
class SwitchScreen extends StatefulWidget {
const SwitchScreen({super.key});
@override
State<SwitchScreen> createState() => _SwitchScreenState();
}
class _SwitchScreenState extends State<SwitchScreen> {
bool check = false;
Widget _buildSwitchListTile(String title, String description, bool currentValue, Function(bool) updateValue) {
return SwitchListTile(
title: Text(title),
value: currentValue,
subtitle: Text(description),
onChanged: updateValue,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Filters'),
),
body: Column(
children: [
Container(
padding: const EdgeInsets.all(20),
child: Text(
'select',
),
),
Expanded(
child: ListView(
children: [
_buildSwitchListTile(
'text',
'description',
check,
(newValue) {
setState(() {
check = newValue;
});
},
),
),
],
),
)
],
),
);
}
}
it worked as I wanted, but I don’t really know why it did. Can anyone explain it to me please!
2
Answers
Updated Code:
Use this code to use multiple SwitchListTile
You can use
SwitchListTile
in newStateful class
and pass 3 parameters. Can also addtypedef
callback if you want to know the state ofcurrentValue
in eachSwitchListTile
.And call the
SwitchClass
in parent Widget.