Skip to content

Instantly share code, notes, and snippets.

@hectorAguero
Last active August 20, 2024 16:24
Show Gist options
  • Save hectorAguero/f66a9d404104d61a74378d08c65f6d2c to your computer and use it in GitHub Desktop.
Save hectorAguero/f66a9d404104d61a74378d08c65f6d2c to your computer and use it in GitHub Desktop.
Example on how to use didUpdateWidget
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool value = false;
@override
Widget build(BuildContext context) => MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(child: AppCheckbox(value: value)),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
setState(() {
value = !value;
});
},
label: Text("Change checkbox value"),
icon: value ? Icon(Icons.check_box) : Icon(Icons.check_box_outline_blank)
),
),
);
}
class AppCheckbox extends StatefulWidget {
const AppCheckbox({
required this.value,
super.key,
});
final bool value;
@override
State<AppCheckbox> createState() => _AppCheckBoxState();
}
class _AppCheckBoxState extends State<AppCheckbox> {
late bool selected = widget.value;
// If this is commented,
// the selected will not be updated when the parameter [value] is updated
@override
void didUpdateWidget(covariant AppCheckbox oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.value != widget.value) {
setState(() {
selected = widget.value;
});
}
}
@override
Widget build(BuildContext context) => Checkbox(
value: selected,
onChanged: (value) {
setState(() {
selected = value ?? false;
});
},
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment