Created
December 4, 2019 17:07
-
-
Save r3dm1ke/a3af56f7c5106b4ed07a05a1cee8f66a to your computer and use it in GitHub Desktop.
Working with checkboxes in Flutter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class TODOState extends State<TODO> { | |
| final List<Task> tasks = []; | |
| void onTaskCreated(String name) { | |
| setState(() { | |
| tasks.add(Task(name)); | |
| }); | |
| } | |
| // A new callback function to toggle task's completion | |
| void onTaskToggled(Task task) { | |
| setState(() { | |
| task.setCompleted(!task.isCompleted()); | |
| }); | |
| } | |
| @override | |
| Widget build(BuildContext context) { | |
| return MaterialApp( | |
| title: 'TODO app', | |
| initialRoute: '/', | |
| routes: { | |
| // Passing the function as a callback | |
| '/': (context) => TODOList(tasks: tasks, onToggle: onTaskToggled), | |
| '/create': (context) => TODOCreate(onCreate: onTaskCreated,), | |
| }, | |
| ); | |
| } | |
| } | |
| class TODOList extends StatelessWidget { | |
| final List<Task> tasks; | |
| final onToggle; | |
| TODOList({@required this.tasks, @required this.onToggle}); | |
| @override | |
| Widget build(BuildContext context) { | |
| return Scaffold( | |
| appBar: AppBar( | |
| title: Text('TODO app'), | |
| ), | |
| body: ListView.builder( | |
| itemCount: tasks.length, | |
| itemBuilder: (context, index) { | |
| // Changed ListTile to CheckboxListTile to have | |
| // the checkbox capability | |
| return CheckboxListTile( | |
| title: Text(tasks[index].getName()), | |
| // Passing a value and a callback for the checkbox | |
| value: tasks[index].isCompleted(), | |
| // The _ in the argument list is there because onChanged expects it | |
| // But we are not using it | |
| onChanged: (_) => onToggle(tasks[index]), | |
| ); | |
| }), | |
| floatingActionButton: FloatingActionButton( | |
| onPressed: () => Navigator.pushNamed(context, '/create'), | |
| child: Icon(Icons.add) | |
| ), | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment