Next we need to create the MyAppState and build our layout. This is all standard boilerplate for a flutter app using Stateful Widgets. We’ll do that by creating a very simple flutter app as follows: import 'package:multi_checkbox_dox_demo/checkbox_model.dart' Ĭonst MyApp() : super(key: createState() => _MyAppState() Ībove we create a basic StatefulWidget named MyApp and call the standard createState() method returning MyAppState. OK, now we have our CheckboxModel, we need to put it to work. I also supplied a handler method that returns the onToggle callback method or null depending on the state of shouldToggle. I also included an isEnabled getter so we can query the checkbox for it’s activity state. When true is passed to enable(), it enables the checkbox. Additionally, there is an enable() method that takes a boolean argument. The toogle() method flips the state of the chackbox each time it is called. The checkbox model includes a constructor that initializes onToggle to the class’ own toggle() method. Void enable(bool state) => shouldToggle = state Here’s the code for checkbox_model.dart: import 'package:flutter/scheduler.dart' Since I also need to disable each checkbox, I added a boolean shouldToggle field to control when the checkbox should be active. So with a plan in hand I created a class that included members for the checkbox title, value, and callback handler. However, here I wanted a more straightforward approach so as not to unduly confuse the noobie I was writing this for. I could have taken any number of other approaches such as using a mixin, extending the Checkbox widget, or using a design pattern (see my articles on Design Patterns in Dart). With that done, I decided to create a model to hold the data and methods needed for each checkbox. The first thing I did was to review what I knew about checkboxes in Flutter. Sometimes the best solution is just a very straightforward one. Since I was dealing with a noobie I didn’t want anything to complex or that would hide aspects of the implementation from the coder. GFCheckBox is a Flutter Checkbox that is a material widget that allows users to select one option from the set of given options. Note that as with all software tasks there are many ways to solve this issue. I didn’t have time at that moment but promised I would get an example done by end of the day. I offered a solution which as is often the case, was met with “Can you show me some code?”. Today I was asked how to implement multiple selectable groups of checkboxes in Flutter. I spend a lot of time on the Flutter Slack channel (thanks Scott!), and I try and help as many people as possible during my breaks from my own work.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |