Only one checkbox to be checked at time in Flutter - flutter

I have a 3 check box in my app, which are formed by looping over the tickbox map, in my Application it allows to select multiple checkboxes but I dont want that to happen , only one should be selected at a time, is there any way to do so in flutter.
below is my code.
class _DashboardFilterState extends State<DashboardFilter> {
void showModalSheet() {
List<Map<String, Object>> tickbox;
timeData = [
{"id": "1", "displayId": "Daily"},
{"id": "2", "displayId": "Weekly"},
{"id": "3", "displayId": "Monthly"}
];
showModalBottomSheet<void>(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
context: context,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter state) {
return createBox(context, timeData, state);
});
});
}
createBox(BuildContext context,List<Map<String, Object>> tickbox, StateSetter state) {
var tickboxdata = tickbox.map<Widget>((data) {
int id = data["id"];
var dispId = data["displayId"];
return buildTimeData(context, id, dispId, state);
}).toList();
return SingleChildScrollView(
child: LimitedBox(
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
// children: metrics,
children: <Widget>[
Container(
child: Column(
children: tickboxdata,
),
),
],
)),
);
}
Widget buildTimeData(
BuildContext context, var id, var disp, StateSetter state) {
return Container(
child: Column(mainAxisSize: MainAxisSize.min,
children: <Widget>[
CheckboxListTile(
value: widget.timeSelected[id],
title: Text(disp),
controlAffinity: ListTileControlAffinity.leading,
onChanged: (bool val) {
manageTimeState(val, id, state);
})
]));
}
void manageTimeState(bool val, var id, StateSetter state) {
state(() {
widget.timeSelected[id] = val;
});
}
let me know if is there any other option to do so thanks

without any package i make the example (null safe)
Output :-
Example code :-
import 'package:flutter/material.dart';
class CheckBoxExample extends StatefulWidget {
const CheckBoxExample({Key? key}) : super(key: key);
#override
State<CheckBoxExample> createState() => _CheckBoxExampleState();
}
class _CheckBoxExampleState extends State<CheckBoxExample> {
String selected = "";
List checkListItems = [
{
"id": 0,
"value": false,
"title": "Sunday",
},
{
"id": 1,
"value": false,
"title": "Monday",
},
{
"id": 2,
"value": false,
"title": "Tuesday",
},
{
"id": 3,
"value": false,
"title": "Wednesday",
},
{
"id": 4,
"value": false,
"title": "Thursday",
},
{
"id": 5,
"value": false,
"title": "Friday",
},
{
"id": 6,
"value": false,
"title": "Saturday",
},
];
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 64.0),
child: Column(
children: [
Column(
children: List.generate(
checkListItems.length,
(index) => CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
contentPadding: EdgeInsets.zero,
dense: true,
title: Text(
checkListItems[index]["title"],
style: const TextStyle(
fontSize: 16.0,
color: Colors.black,
),
),
value: checkListItems[index]["value"],
onChanged: (value) {
setState(() {
for (var element in checkListItems) {
element["value"] = false;
}
checkListItems[index]["value"] = value;
selected =
"${checkListItems[index]["id"]}, ${checkListItems[index]["title"]}, ${checkListItems[index]["value"]}";
});
},
),
),
),
const SizedBox(height: 100.0),
Text(
selected,
style: const TextStyle(
fontSize: 22.0,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
],
),
),
);
}
}

please use package https://pub.dev/packages/grouped_buttons
In onSelected, remove first selected item if more than one selected
code snippet
List<String> _checked = [];
...
CheckboxGroup(
labels: <String>[
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
],
disabled: ["Wednesday", "Friday"],
checked: _checked,
onChange: (bool isChecked, String label, int index) =>
print("isChecked: $isChecked label: $label index: $index"),
onSelected: (List selected) => setState(() {
if (selected.length > 1) {
selected.removeAt(0);
print('selected length ${selected.length}');
} else {
print("only one");
}
_checked = selected;
}),
),
full code
/*
Name: Akshath Jain
Date: 3/15/19
Purpose: example app for the grouped buttons package
*/
import 'package:flutter/material.dart';
import 'package:grouped_buttons/grouped_buttons.dart';
void main() => runApp(GroupedButtonExample());
class GroupedButtonExample extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Grouped Buttons Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<String> _checked = []; //["A", "B"];
String _picked = "Two";
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Grouped Buttons Example"),
),
body: _body(),
);
//
}
Widget _body() {
return ListView(children: <Widget>[
//--------------------
//SIMPLE USAGE EXAMPLE
//--------------------
//BASIC CHECKBOXGROUP
Container(
padding: const EdgeInsets.only(left: 14.0, top: 14.0),
child: Text(
"Basic CheckboxGroup",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
),
),
CheckboxGroup(
labels: <String>[
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
],
disabled: ["Wednesday", "Friday"],
checked: _checked,
onChange: (bool isChecked, String label, int index) =>
print("isChecked: $isChecked label: $label index: $index"),
onSelected: (List selected) => setState(() {
if (selected.length > 1) {
selected.removeAt(0);
print('selected length ${selected.length}');
} else {
print("only one");
}
_checked = selected;
}),
),
//BASIC RADIOBUTTONGROUP
Container(
padding: const EdgeInsets.only(left: 14.0, top: 14.0),
child: Text(
"Basic RadioButtonGroup",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
),
),
RadioButtonGroup(
labels: [
"Option 1",
"Option 2",
],
disabled: ["Option 1"],
onChange: (String label, int index) =>
print("label: $label index: $index"),
onSelected: (String label) => print(label),
),
//--------------------
//CUSTOM USAGE EXAMPLE
//--------------------
///CUSTOM CHECKBOX GROUP
Container(
padding: const EdgeInsets.only(left: 14.0, top: 14.0, bottom: 14.0),
child: Text(
"Custom CheckboxGroup",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
),
),
CheckboxGroup(
orientation: GroupedButtonsOrientation.HORIZONTAL,
margin: const EdgeInsets.only(left: 12.0),
onSelected: (List selected) => setState(() {
_checked = selected;
}),
labels: <String>[
"A",
"B",
],
checked: _checked,
itemBuilder: (Checkbox cb, Text txt, int i) {
return Column(
children: <Widget>[
Icon(Icons.polymer),
cb,
txt,
],
);
},
),
///CUSTOM RADIOBUTTON GROUP
Container(
padding: const EdgeInsets.only(left: 14.0, top: 14.0, bottom: 14.0),
child: Text(
"Custom RadioButtonGroup",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
),
),
RadioButtonGroup(
orientation: GroupedButtonsOrientation.HORIZONTAL,
margin: const EdgeInsets.only(left: 12.0),
onSelected: (String selected) => setState(() {
_picked = selected;
}),
labels: <String>[
"One",
"Two",
],
picked: _picked,
itemBuilder: (Radio rb, Text txt, int i) {
return Column(
children: <Widget>[
Icon(Icons.public),
rb,
txt,
],
);
},
),
]);
}
}
working demo

Related

Select single checkbox using checkBoxListTile - Flutter

Am trying to select one or more check boxes from a list of check boxes, i have found that the best option is using the checkBoxListTile widget to implement this.
First i have defined a list and used the widget as follows:
List<String> _texts = ["google.com", "youtube.com", "yahoo.com", "gmail.com"];
Expanded(
child: ListView(
children: _texts
.map((text) => CheckboxListTile(
title: Text(text),
value: _isChecked,
onChanged: (val) {
setState(() {
_isChecked = val;
});
},
))
.toList(),
),
),
check boxes are displayed fine but whenever i click one checkbox all are checked, how can i handle choosing one or more check boxes from the list?
Thank you
Try below code hope its help to you I have try it other way
Only Single Checkbox Selected:
Your List :
List _texts = [
{
"value": false,
"site": "google.com",
},
{
"value": false,
"site": "youtube.com",
},
{
"value": false,
"site": "yahoo.com",
},
{
"value": false,
"site": "gmail.com",
},
];
Your Widget:
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 64.0),
child: Column(
children: List.generate(
_texts.length,
(index) => CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
contentPadding: EdgeInsets.zero,
dense: true,
title: Text(
_texts[index]["site"],
style: const TextStyle(
fontSize: 16.0,
color: Colors.black,
),
),
value: _texts[index]["value"],
onChanged: (value) {
setState(() {
for (var element in _texts) {
element["value"] = false;
}
_texts[index]["value"] = value;
});
},
),
),
),
),
Full Code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Flutter Single Checkbox Example"),
),
body: SafeArea(
child: Center(
child: CheckboxWidget(),
))),
);
}
}
class CheckboxWidget extends StatefulWidget {
#override
CheckboxWidgetState createState() => new CheckboxWidgetState();
}
class CheckboxWidgetState extends State {
List _texts = [
{
"value": false,
"site": "google.com",
},
{
"value": false,
"site": "youtube.com",
},
{
"value": false,
"site": "yahoo.com",
},
{
"value": false,
"site": "gmail.com",
},
];
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 64.0),
child: Column(
children: List.generate(
_texts.length,
(index) => CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
contentPadding: EdgeInsets.zero,
dense: true,
title: Text(
_texts[index]["site"],
style: const TextStyle(
fontSize: 16.0,
color: Colors.black,
),
),
value: _texts[index]["value"],
onChanged: (value) {
setState(() {
for (var element in _texts) {
element["value"] = false;
}
_texts[index]["value"] = value;
});
},
),
),
),
);
}
}
Result Screen->
Multiple Checkbox Selection
Your List/Map
Map<String, bool> values = {
'google.com': false,
'youtube.com': false,
'yahoo.com': false,
'gmail.com': false,
};
Your Function:
var tmpArray = [];
getCheckboxItems() {
values.forEach((key, value) {
if (value == true) {
tmpArray.add(key);
}
});
print(tmpArray);
tmpArray.clear();
}
Your Widget:
Column(
children: <Widget>[
ListView(
shrinkWrap: true,
children: values.keys.map((String key) {
return new CheckboxListTile(
title: new Text(key),
value: values[key],
onChanged: (value) {
setState(() {
values[key] = value!;
});
},
);
}).toList(),
),
const SizedBox(
height: 100,
),
ElevatedButton(
child: Text(
" Checkbox Items ",
style: TextStyle(fontSize: 18),
),
onPressed: getCheckboxItems,
),
],
)
Full Example
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Flutter Multiple Checkbox Example"),
),
body: SafeArea(
child: Center(
child: CheckboxWidget(),
))),
);
}
}
class CheckboxWidget extends StatefulWidget {
#override
CheckboxWidgetState createState() => new CheckboxWidgetState();
}
class CheckboxWidgetState extends State {
Map<String, bool> values = {
'google.com': false,
'youtube.com': false,
'yahoo.com': false,
'gmail.com': false,
};
var tmpArray = [];
getCheckboxItems() {
values.forEach((key, value) {
if (value == true) {
tmpArray.add(key);
}
});
print(tmpArray);
tmpArray.clear();
}
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
ListView(
shrinkWrap: true,
children: values.keys.map((String key) {
return new CheckboxListTile(
title: new Text(key),
value: values[key],
onChanged: (value) {
setState(() {
values[key] = value!;
});
},
);
}).toList(),
),
const SizedBox(
height: 100,
),
ElevatedButton(
child: Text(
" Checkbox Items ",
style: TextStyle(fontSize: 18),
),
onPressed: getCheckboxItems,
),
],
);
}
}
Result Screen->
Refer Video Tutorial for Flutter Multiselect Dropdown Checkbox on YouTube
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: _title,
home: CheckBoxExample(),
);
}
}
class CheckBoxExample extends StatefulWidget {
const CheckBoxExample({Key? key}) : super(key: key);
#override
State<CheckBoxExample> createState() => _CheckBoxExampleState();
}
class _CheckBoxExampleState extends State<CheckBoxExample> {
String selectedMonth = "";
List checkListItems = [
{
"id": 0,
"value": false,
"monthName": "January",
},
{
"id": 1,
"value": false,
"monthName": "Febuary",
},
{
"id": 2,
"value": false,
"monthName": "March",
},
{
"id": 3,
"value": false,
"monthName": "April",
},
{
"id": 4,
"value": false,
"monthName": "May",
},
{
"id": 5,
"value": false,
"monthName": "June",
},
{
"id": 6,
"value": false,
"monthName": "July",
},
{
"id": 7,
"value": false,
"monthName": "August",
},
{
"id": 8,
"value": false,
"monthName": "September",
},
{
"id": 9,
"value": false,
"monthName": "October",
},
{
"id": 10,
"value": false,
"monthName": "November",
},
{
"id": 11,
"value": false,
"monthName": "December",
},
];
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 64.0),
child: Column(
children: [
Text(
selectedMonth,
style: const TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 85.0),
Column(
children: List.generate(
checkListItems.length,
(index) => CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
contentPadding: EdgeInsets.zero,
dense: true,
title: Text(
checkListItems[index]["monthName"],
style: const TextStyle(
fontSize: 16.0,
color: Colors.black,
),
),
value: checkListItems[index]["value"],
onChanged: (value) {
setState(() {
for (var element in checkListItems) {
element["value"] = false;
}
checkListItems[index]["value"] = value;
selectedMonth ="${checkListItems[index]["id"]+1}, ${checkListItems[index]["monthName"]}";
});
},
),
),
),
],
),
),
);
}
}
Output
The value parameter for in CheckboxListTile is how widget knows whether checkbox is checked or not. When you give all of them same value, all of their state changes.
You can keep a seperate list to keep track of if the specific checkbox is checked.

Flutter Auto Countdown Implementation for Fitness Workout

I'm working on a Flutter Workout App and I'm having some issues implementing the Workout Sequence and Timer.
I was able to implement the auto countdown and workout sequence however, the countdown skips numbers between and the workout sequence runs only for the first 2 sets.
For example, if an exercise has 4 sets, the cycle only runs for the first two and it's glitchy. I need help with optimized code to help me achieve the workout sequence
JSON DATA
{
"data": {
"day1": [
{
"id": 1,
"title": "Reclining Triceps Press",
"equipment": "Pull Up Bar",
"level": "Beginner",
"reps": "15",
"rest": "45 Seconds",
"sets": "4",
"image": "https://wicombit.com/demo/fitpro/images/exercise_1519941887.jpg",
"video": null,
},
{
"id": 10,
"title": "Plank with Arm Raise",
"equipment": "Pull Up Bar",
"level": "Intermediate",
"reps": "12",
"rest": "30 Seconds",
"sets": "3",
"image": "https://wicombit.com/demo/fitpro/images/exercise_1519938568.jpg",
"video": null,
},
{
"id": 3,
"title": "90-degree Static Hold",
"equipment": "Pull Up Bar",
"level": "Beginner",
"reps": "12",
"rest": "45 Seconds",
"sets": "3",
"image": "https://wicombit.com/demo/fitpro/images/exercise_1519940878.jpg",
"video": null,
},
{
"id": 5,
"title": "Single-arm Medicine Ball Pushup",
"equipment": "Kettlebells",
"level": "Elite",
"reps": "8",
"rest": "45 Seconds",
"sets": "3",
"image": "https://wicombit.com/demo/fitpro/images/exercise_1519940316.jpg",
"video": null,
"status": "draft"
}
],
}
}
I have tried the below implementation but not getting the results I want.
Dart Implementation
class WorkouStartSequenceScreen extends StatefulWidget {
final exercise;
WorkouStartSequenceScreen({super.key, required this.exercise});
#override
State<WorkouStartSequenceScreen> createState() =>
_WorkouStartSequenceScreenState();
}
class _WorkouStartSequenceScreenState extends State<WorkouStartSequenceScreen> {
late Timer _startTimer;
late Timer _restTimer;
late int totalNoOfExercisesInDay;
int currentExerciseIndex = 0;
late int totalNoOfSets;
late int totalNoOfReps;
late int totalRestTime;
int currentSetNo = 0;
int currentRepNo = 0;
int currentRestTime = 0;
bool dayWorkoutComplete = false;
int startUpCountdown = 10;
StreamController<int> _startEvents = BehaviorSubject();
StreamController<int> _restEvents = BehaviorSubject();
#override
void initState() {
totalNoOfExercisesInDay = widget.exercise.length;
totalNoOfReps = int.parse(widget.exercise[currentExerciseIndex].reps);
totalNoOfSets = int.parse(widget.exercise[currentExerciseIndex].sets);
totalRestTime = int.parse(widget.exercise[currentExerciseIndex].rest
.replaceAll(new RegExp(r'[^0-9]'), ''));
currentRestTime = totalRestTime;
_startEvents.add(startUpCountdown);
super.initState();
}
#override
void dispose() {
_startTimer.cancel();
_restTimer.cancel();
// _startEvents.close();
// _restEvents.close();
super.dispose();
}
void _showStartupDialog() async {
_startTimer = Timer.periodic(Duration(seconds: 1), (timer) {
(startUpCountdown > 0) ? startUpCountdown-- : _startTimer.cancel();
_startEvents.add(startUpCountdown);
});
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext builderContext) {
_startTimer = Timer(Duration(seconds: 10), () {
Navigator.of(context).pop();
});
return AlertDialog(
backgroundColor: AppStyles.primaryColor,
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Your workout starts in',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white, fontSize: SizeConfig.font20)),
SizedBox(height: SizeConfig.height20),
StreamBuilder<int>(
stream: _startEvents.stream,
builder:
(BuildContext context, AsyncSnapshot<int> snapshot) {
return Text('${snapshot.data.toString()}',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: SizeConfig.font50));
}),
],
),
);
}).then((val) {
if (_startTimer.isActive) {
_startTimer.cancel();
}
});
}
void startRestTimer() async {
_restTimer = Timer.periodic(Duration(seconds: 1), (timer) {
(currentRestTime > 0) ? currentRestTime-- : _restTimer.cancel();
_restEvents.add(currentRestTime);
});
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext builderContext) {
_restTimer = Timer(Duration(seconds: totalRestTime), () {
Navigator.of(context).pop();
});
return AlertDialog(
backgroundColor: AppStyles.primaryColor,
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('REST',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white, fontSize: SizeConfig.font20)),
SizedBox(height: SizeConfig.height20),
StreamBuilder<int>(
stream: _restEvents.stream,
builder:
(BuildContext context, AsyncSnapshot<int> snapshot) {
return Text('${snapshot.data.toString()}',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: SizeConfig.font50));
}),
],
),
);
}).then((_) {
print("Next Set Starting");
setState(() {
currentRepNo = 0;
currentRestTime = int.parse(widget.exercise[currentExerciseIndex].rest
.replaceAll(new RegExp(r'[^0-9]'), ''));
startExercise();
});
_restTimer.cancel();
});
}
void startExercise() {
const oneSec = const Duration(seconds: 2);
new Timer.periodic(
oneSec,
(Timer timer) {
if (currentRepNo == totalNoOfReps) {
setState(() {
timer.cancel();
startRestTimer();
currentSetNo++;
if (currentSetNo == totalNoOfSets) {
currentExerciseIndex++;
}
});
} else {
setState(() {
currentRepNo++;
});
}
},
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey[100],
appBar: AppBar(
backgroundColor: AppStyles.primaryDark,
leading: GestureDetector(
onTap: () => Get.back(),
child: Icon(FontAwesomeIcons.xmark,
color: AppStyles.appSecondaryColor)),
),
body: Column(children: [
Image.network(widget.exercise[currentExerciseIndex].image),
SizedBox(height: SizeConfig.height20),
TitleTextWidget(
titleText: widget.exercise[currentExerciseIndex].title,
titleSize: SizeConfig.font25,
titleTextMaxLines: 3),
SizedBox(height: SizeConfig.height50),
Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
Column(children: [
Row(children: [
TitleTextWidget(
titleText: ("$currentRepNo"),
titleSize: SizeConfig.font80,
),
Text("/", style: TextStyle(fontSize: SizeConfig.font80)),
DescriptionTextWidget(
descriptionText: widget.exercise[currentExerciseIndex].reps,
descriptionSize: SizeConfig.font80,
fontFamily: 'Raleway'),
]),
SizedBox(height: SizeConfig.height20),
DescriptionTextWidget(
descriptionText: 'Reps',
fontFamily: 'Raleway',
descriptionSize: SizeConfig.font30)
]),
Column(children: [
Row(children: [
TitleTextWidget(
titleText: currentSetNo.toString(),
titleSize: SizeConfig.font80,
),
Text("/", style: TextStyle(fontSize: SizeConfig.font80)),
DescriptionTextWidget(
descriptionText: widget.exercise[currentExerciseIndex].sets,
descriptionSize: SizeConfig.font80,
fontFamily: 'Raleway'),
]),
SizedBox(height: SizeConfig.height20),
DescriptionTextWidget(
descriptionText: 'Sets',
fontFamily: 'Raleway',
descriptionSize: SizeConfig.font30)
])
]),
SizedBox(height: SizeConfig.height30),
GestureDetector(
onTap: () {
_showStartupDialog();
Future.delayed(const Duration(seconds: 10), () {
startExercise();
});
},
child: Container(
height: SizeConfig.height70,
width: double.maxFinite,
margin: EdgeInsets.symmetric(
horizontal: SizeConfig.width20, vertical: SizeConfig.height5),
decoration: BoxDecoration(
color: AppStyles.primaryColor,
borderRadius: BorderRadius.circular(
SizeConfig.radius15,
)),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: SizeConfig.width40,
vertical: SizeConfig.height10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(FontAwesomeIcons.play, color: Colors.white),
SizedBox(width: SizeConfig.width10),
Text(
"Start",
style: TextStyle(
color: Colors.white,
fontSize: SizeConfig.font25,
fontWeight: FontWeight.w500),
),
],
),
),
),
)
]),
);
}
}

display sticky header list from api

Greeting to all,
I have made a list view using a sticky header where I am displaying the header list and sublist that I am getting from the API response. i am getting the data but I am stuck for displaying it in tile or card list like wise.
below is the image of how I am getting the data -:
and below is the code for sticky header -:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:sticky_headers/sticky_headers.dart';
import 'package:vcura/Model/Vaccination/Get_Vaccine.dart';
import 'package:vcura/Model/Vaccination/Get_Vaccine_ByID.dart';
import 'package:vcura/Provider/auth_provider.dart';
import 'package:vcura/Screens/home/collapsibleDrawer.dart';
import 'package:vcura/Services/Vaccination/Vaccineservice.dart';
import 'package:vcura/Widgets/custom_loader.dart';
class VaccinationPage extends StatefulWidget {
#override
_VaccinationPageState createState() => _VaccinationPageState();
}
class _VaccinationPageState extends State<VaccinationPage>
with SingleTickerProviderStateMixin {
bool isloading = false;
GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
bool drawerOpen = true;
var newFormat = DateFormat("dd-MM-yy");
GetVaccine _vaccine = GetVaccine();
GetVaccineById vaccineById = GetVaccineById();
VaccineService vaccineService = VaccineService();
var idSet = <String>{};
var header = <dynamic>[];
// var subtitle = [];
List<VaccineModel> subtitle = [];
#override
void initState() {
super.initState();
getdata();
}
Future getdata() async {
setState(() {
isloading = true;
});
String authToken = Provider.of<AuthProvider>(context, listen: false).token;
GetVaccine vaccine = await vaccineService.Getvaccine(authToken);
setState(() {
_vaccine = vaccine;
for (var d in _vaccine.data) {
if (idSet.add(d.vaccineAgeCriteria)) {
header.add(d.vaccineAgeCriteria);
}
}
});
setState(() {
isloading = false;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
drawerScrimColor: Colors.transparent,
extendBody: true,
drawer: ComplexDrawer(),
appBar: AppBar(
leading: InkWell(
child: Icon(
Icons.menu,
color: Colors.indigo,
),
onTap: () {
if (drawerOpen) {
scaffoldKey.currentState.openDrawer();
} else {
return null;
}
},
),
centerTitle: true,
title: Text(
'Vaccination',
style: GoogleFonts.ubuntu(
fontSize: 30,
color: Colors.indigo,
),
),
backgroundColor: Colors.white,
actions: [
InkWell(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Icon(
Icons.search,
color: Colors.indigo,
size: 30,
),
),
onTap: () {},
),
],
elevation: 1,
),
body: isloading
? CustomLoader(size: 50, color: Colors.indigoAccent)
: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
child: Container(
height: MediaQuery.of(context).size.height,
child: ListView.builder(itemBuilder: (context, index) {
subtitle = _vaccine.data
.where((i) => i.vaccineAgeCriteria == header[index])
.toList();
print(subtitle.map((e) => e.vaccine));
return StickyHeaderBuilder(
builder: (context, stuckAmount) {
stuckAmount = stuckAmount.clamp(0.0, 1.0);
return Container(
height: 100.0 - (50 * (1 - stuckAmount)),
color:
Color.lerp(Colors.blue, Colors.red, stuckAmount),
padding: EdgeInsets.symmetric(horizontal: 16.0),
alignment: Alignment.centerLeft,
child: Text(
'${header[index]}',
style: const TextStyle(color: Colors.white),
),
);
},
content: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: List<int>.generate(1, (index) => index)
.map(
(item) => Container(
height: subtitle.length * 50.0,
width: MediaQuery.of(context).size.width,
child: ListTile(
title: Text(
'${subtitle.map((e) => e.vaccine)}'),
), //_vaccine.data[index].vaccine
),
)
.toList(),
),
),
);
})),
),
);
}
}
below is a sample of data that I am getting -
"data": [
{
"id": "0616c0b6-d798-08d974ba51cb",
"vaccine": "Bacillus Calmette–Guérin (BCG)",
"vaccineAgeCriteria": "Birth",
"dose": 1,
"vaccineDate": "1996-12-31T18:30:00"
},
{
"id": "1e109992-d79b-08d974ba51cb",
"vaccine": "Diptheria, Tetanus and Pertussis vaccine (DTwP 1)",
"vaccineAgeCriteria": "6 weeks",
"dose": 1,
"vaccineDate": "0001-01-01T00:00:00"
},
{
"id": "a985b9d5-d7a3-08d974ba51cb",
"vaccine": "Haemophilus influenzae type B (Hib 2)",
"vaccineAgeCriteria": "10 weeks",
"dose": 1,
"vaccineDate": "0001-01-01T00:00:00"
},
{
"id": "1597403a-d7a4-08d974ba51cb",
"vaccine": "Rotavirus 2",
"vaccineAgeCriteria": "10 weeks",
"dose": 1,
"vaccineDate": "0001-01-01T00:00:00"
},
],
"exceptionInfo": null,
"message": null,
"messages": null,
"isSuccess": true
}
please help.
Wrap your ListTile with the ListView.builder.
ListView.builder(
shrinkWrap: true,
physics: ScrollPhysics(),
itemCount: subtitle.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(subtitle[index].vaccine),
);
},
),

How to select multiple checkboxes in flutter in checkboxlisttile

Can anyone please tell me how do I select multiple options in checkboxlisttile.
Here I am able to click only one option. I want to set the status column in note table in database as completed when i check the particular item.
(Actually I want to select the item as completed and display it under another tab called completed. checkboxlisttile is created dynamically i.e from database. When a new note is added it is displayed in this listview.)
note_info.dart //this is the screen where notes are displayed i.e listview
import 'dart:io';
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/models/customer_model.dart';
import 'package:vers2cts/services/db_service.dart';
import 'package:vers2cts/utils/db_helper.dart';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'new_note.dart';
class Note_Info extends StatefulWidget{
final String appBarTitle;
final CustomerModel customer;
//Note_Info();
Note_Info(this. customer, this.appBarTitle);
#override
State<StatefulWidget> createState() {
//return Note_InfoState();
return Note_InfoState(this. customer,this.appBarTitle);
}
}
class Note_InfoState extends State<Note_Info> {
DBService dbService = DBService();
List<NoteModel> noteList;
int count = 0;
static final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
NoteModel note=NoteModel();
String appBarTitle;
CustomerModel customer=new CustomerModel();
Note_InfoState(this.customer, this.appBarTitle);
bool rememberMe = false;
DateTime _date = DateTime.now();
TextEditingController custfNameController = TextEditingController();
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
updateListView();
if (noteList == null) {
noteList = List<NoteModel>();
updateListView();
}
TextStyle titleStyle = Theme.of(context).textTheme.subhead;
var height = MediaQuery.of(context).size.height;
var name=customer.first_name+" "+customer.last_name;
custfNameController.text = name;
return DefaultTabController(
length: 4,
child: Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: Icon(
Icons.add,
),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => NewNote(customer,note)));
},
)
],
),
body: Container(
child: Column(
children: <Widget>[
TextField(controller: custfNameController,
style: TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
textAlign: TextAlign.center),
Padding(
padding: const EdgeInsets.all(15.0),
child: Row(children: [
ImageProfile(customer.cust_photo),
Padding(
padding: const EdgeInsets.only(left: 30.0),
child: IconButton(
icon: Icon(
Icons.call,
color: Colors.green,
size: 45,
),
onPressed: () {
},
),
),
],),
),
SizedBox(
height: 50,
child: AppBar(
bottom: TabBar(
tabs: [
Tab(
text: "All",
),
Tab(
text: "Pending",
),
Tab(
text: "Cancelled",
),
Tab(
text: "Completed",
),
],
),
),
),
// create widgets for each tab bar here
Expanded(
child: TabBarView(
children: [
// first tab bar view widget
Container(
child: getNotecheckList()
),
// second tab bar view widget
Container(
),
Container(
child: Center(
child: Text(
'Cancelled',
),
),
),
Container(
child: Center(
child: Text(
'Completed',
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 55.0,
width: 200,
child: RaisedButton(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Theme
.of(context)
.primaryColorDark,
textColor: Colors.white,
child: Text('Save', textScaleFactor: 1.5,),
onPressed: () {
setState(() {
//_reset();
});
},
),
),
),
]
),
)
));
}
Widget ImageProfile(String fileName) {
return Center(
child: CircleAvatar(
radius: 80.0,
backgroundImage: fileName == null
?AssetImage('images/person_icon.jpg')
:FileImage(File(customer.cust_photo))),
);
}
Future<void> updateListView() {
final Future<Database> dbFuture = DB.init();
dbFuture.then((database) {
int cid=customer.cust_id;
Future<List<NoteModel>> noteListFuture = dbService.getCustomerNotes(cid);
noteListFuture.then((noteList) {
setState(() {
this.noteList = noteList;
this.count = noteList.length;
});
});
});
}
int _isChecked=-1;
ListView getNotecheckList() {
return ListView.builder(
itemCount: count,
itemBuilder: (BuildContext context, int position) {
return Card(
color: Colors.white,
elevation: 2.0,
child: CheckboxListTile(
title: Text(this.noteList[position].note),
subtitle: Text(this.noteList[position].actn_on),
//secondary: const Icon(Icons.web),
value: position== _isChecked,
onChanged: (bool value) {
setState(() {
_isChecked = value?position:-1;
});
},
controlAffinity: ListTileControlAffinity.leading,
),
);
},
);
}
}
new_note.dart //this is where new note is added.
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';
import 'package:smooth_star_rating/smooth_star_rating.dart';
import 'package:intl/intl.dart';
import 'package:vers2cts/models/customer_model.dart';
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/services/db_service.dart';
import 'package:vers2cts/utils/form_helper.dart';
class NewNote extends StatefulWidget{
final NoteModel note;
final CustomerModel customer;
NewNote(this.customer,this. note);
//Dropdown
/*
final String label;
final Function(Color) onChanged;
final double height;
final double width;
NewNote.fordropdwn({
Key key,
this.onChanged,
this.height = 25,
this.width = 150,
this.label,
}) : super(key: key);*/
#override
State<StatefulWidget> createState() {
//return New_NoteState(this.customer);
return New_NoteState(this.customer,this.note);
}
}
class New_NoteState extends State<NewNote> with SingleTickerProviderStateMixin{
New_NoteState(this.customer,this.note);
NoteModel note=new NoteModel();
CustomerModel customer=new CustomerModel();
TextEditingController NoteController=TextEditingController();
TextEditingController custfNameController = TextEditingController();
DateTime _reminderDate = DateTime.now();
DBService dbService=new DBService();
SpeedDial _speedDial(){
return SpeedDial(
// child: Icon(Icons.add),
animatedIcon: AnimatedIcons.add_event,
animatedIconTheme: IconThemeData(size: 24.0),
backgroundColor: Colors.yellow,
curve: Curves.easeInCirc,
children: [
SpeedDialChild(
child: Icon(Icons.location_on,color: Colors.yellow,),
//backgroundColor: Theme.of(context).primaryColor,
label: 'Add Location',
//labelBackgroundColor:Theme.of(context).primaryColor,
),
SpeedDialChild(
child: Icon(Icons.keyboard_voice),
//backgroundColor: Colors.yellow,
label: 'Add voice',
//labelBackgroundColor: Colors.yellow
),
SpeedDialChild(
child: Icon(Icons.attachment_outlined,color :Colors.redAccent),
//backgroundColor:Theme.of(context).primaryColorLight,
label: 'Add File',
// labelBackgroundColor: Theme.of(context).primaryColorLight
),
SpeedDialChild(
child: Icon(Icons.image,color: Colors.lightBlue,),
//backgroundColor: Colors.yellow,
label: 'Add Image',
// labelBackgroundColor: Colors.yellow,
),
],
);
}
//for DropDownMenu
Color value=Colors.red;
final List<Color> colors = [
Colors.red,
Colors.blue,
Colors.green,
Colors.yellow,
Colors.pink,
Colors.purple,
Colors.brown,
];
//for Switch
bool isSwitched = false;
var textValue = 'Switch is OFF';
void toggleSwitch(bool value) {
if(isSwitched == false)
{
setState(() {
isSwitched = true;
note.rmnd_ind=1;
//this.note.remindOn = _reminderDate.toString();
});
}
else
{
setState(() {
isSwitched = false;
note.rmnd_ind=0;
});
}
}
#override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;
var name=customer.first_name+customer.last_name;
custfNameController.text = name;
return WillPopScope(
onWillPop: () {
// Write some code to control things, when user press Back navigation button in device navigationBar
moveToLastScreen();
},
child: Scaffold(
appBar:AppBar(),
body:ListView(
children: <Widget>[
SizedBox(
height: 2.0,
),
TextField(controller: custfNameController,
style: TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold),
textAlign: TextAlign.center),
Align(
alignment: Alignment.centerLeft,
child: Text("Add New",textAlign: TextAlign.left,
style: TextStyle(fontSize: 22,fontWeight: FontWeight.bold),),
),
SizedBox(
height: 2.0,
),
Divider(),
SizedBox(
height: 2.0,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
controller: NoteController,
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: const BorderSide(width: 2.0),)),
keyboardType: TextInputType.multiline,
minLines: 5,//Normal textInputField will be displayed
maxLines: 5, // when user presses enter it will adapt to it
onChanged: (value) {
this.note.note = value;
},
),
),
TableCalendar(
selectedDayPredicate: (day) {
return isSameDay(_reminderDate, day);
},
onDaySelected: (selectedDay, focusedDay) {
setState(() {
String _reminderDate = DateFormat('dd-MM-yyyy').format(selectedDay);
note.actn_on=_reminderDate.toString();
});
},// Set initial date
focusedDay: DateTime.now(),
firstDay: DateTime.utc(2010, 10, 16),
lastDay: DateTime.utc(2030, 3, 14),),
SizedBox(
height: height*0.03,
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Row(//mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text("Remind me",style: TextStyle(fontSize: 20),),
Padding(
padding: const EdgeInsets.only(left:80.0),
child: Container(
child: Switch(
onChanged: toggleSwitch,
value: isSwitched,
//activeColor: Colors.blue,
//activeTrackColor: Colors.yellow,
//inactiveThumbColor: Colors.redAccent,
//inactiveTrackColor: Colors.orange,
),
),
),
],),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Row(mainAxisAlignment: MainAxisAlignment.start,
children:<Widget>[
Text("Priority",style: TextStyle(fontSize: 20.0),),
Padding(
padding: const EdgeInsets.only(left:20.0),
child: Container(
child: SmoothStarRating(
size: height=50.0,
allowHalfRating: false,
onRated: (value) {
this.note.prty=value;
print("rating value -> $value");
},
),
),
)]),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Row(mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text("Color",style: TextStyle(fontSize: 20),),
Padding(
padding: const EdgeInsets.only(left:80.0),
child: Container(
child: DropdownButton<Color>(
value: value,
//hint: Text(widget.label ?? ''),
onChanged: (color) {
setState(() => value = color);
//widget.onChanged(color);
},
items: colors.map((e) => DropdownMenuItem(
value: e,
child: Container(
// width: 60.0,
//height: 10.0,
width: 60.0,
// height: widget.height,
color: e,
),
),
)
.toList(),
),
),
),
],),
),
SizedBox(
height: height*0.08,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 55.0,
width: 200,
child: RaisedButton(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
color: Theme.of(context).primaryColorDark,
textColor: Colors.white,
child: Text('Save',textScaleFactor: 1.5,),
onPressed: (){
setState(() {
_save();
});
},
),
),
),
],
),
floatingActionButton:_speedDial(),
));
}
void moveToLastScreen() {
Navigator.pop(context, true);
}
void _save() async {
moveToLastScreen();
note.cust_id=customer.cust_id;
print(customer.cust_id);
print(note.cust_id);
int result;
if (note.note_id != null) { // Case 1: Update operation
result = await dbService.updateNote(note);
} else { // Case 2: Insert Operation
result = await dbService.insertNote(note);
}
if (result != 0) { // Success
FormHelper.showAlertDialog(context,'Status', 'Note Saved Successfully');
} else { // Failure
FormHelper.showAlertDialog(context,'Status', 'Problem Saving Note');
}
}
}
db_service.dart
import 'package:vers2cts/models/customer_model.dart';
import 'package:vers2cts/models/languages_model.dart';
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/models/user_model.dart';
import 'package:vers2cts/utils/db_helper.dart';
class DBService {
Future<int> insertNote(NoteModel note) async {
await DB.init();
var result = await DB.insert(NoteModel.table, note);
return result;
}
Future<List<NoteModel>> getCustomerNotes(int customer) async {
await DB.init();
var res = await DB.rawQuery("note WHERE cust_id = '$customer'");
int count = res.length;
List<NoteModel> notelist = List<NoteModel>();
// For loop to create a 'Note List' from a 'Map List'
for (int i = 0; i < count; i++) {
notelist.add(NoteModel.fromMap(res[i]));
}
return notelist;
}
}
note_model.dart
import 'model.dart';
class NoteModel extends Model {
static String table = 'note';
bool isSelected=false;
int note_id;
int cust_id;
String note;
String actn_on;
int rmnd_ind;
double prty;
String colr;
String sts;
int id;
String cre_date;
String cre_by;
String mod_date;
String mod_by;
int txn_id;
int delete_ind;
NoteModel({
this.note_id,
this.cust_id,
this.note,
this.actn_on,
this.rmnd_ind,
this.prty,
this.colr,
this.sts,
this.id,
this.cre_date,
this.cre_by,
this.mod_date,
this.mod_by,
this.txn_id,
this.delete_ind
});
static NoteModel fromMap(Map<String, dynamic> map) {
return NoteModel(
note_id: map["note_id"],
cust_id: map['cust_id'],
note: map['note'].toString(),
actn_on: map['actn_on'].toString(),
rmnd_ind: map['rmnd_ind'],
prty: map['prty'],
colr: map['colr'].toString(),
sts: map['sts'].toString(),
id: map['id'],
cre_date: map['cre_date'].toString(),
cre_by: map['cre_by'].toString(),
mod_date: map['mod_date'].toString(),
mod_by: map['mod_by'].toString(),
txn_id: map['txn_id'],
delete_ind: map['delete_ind'],
);
}
Map<String, dynamic> toMap() {
Map<String, dynamic> map = {
'note_id': note_id,
'cust_id': cust_id,
'note':note,
'actn_on': actn_on,
'rmnd_ind': rmnd_ind,
'prty': prty,
'colr': colr,
'sts':sts,
'id': id,
'cre_date': cre_date,
'cre_by': cre_by,
'mod_date':mod_date,
'mod_by':mod_by,
'txn_id':txn_id,
'delete_ind': delete_ind
};
if (note_id != null) {
map['note_id'] = note_id;
}
return map;
}
}
db_helper.dart
import 'dart:async';
import 'package:vers2cts/models/model.dart';
import 'package:path/path.dart' as p;
import 'package:sqflite/sqflite.dart';
abstract class DB {
static Database _db;
static int get _version => 1;
static Future<Database> init() async {
if (_db != null) {
return _db;
}
try {
var databasesPath = await getDatabasesPath();
String _path = p.join(databasesPath, 'CTS.db');
_db = await openDatabase(_path, version: _version, onCreate: onCreate);
print('db location:'+_path);
} catch (ex) {
print(ex);
}
}
static void onCreate(Database db, int version) async {
await db.execute(
'CREATE TABLE note (note_id INTEGER PRIMARY KEY,cust_id INTEGER, '
'note TEXT, '
'actn_on TEXT, rmnd_ind INTEGER, prty REAL, colr TEXT,'
'sts TEXT,'
'id INTEGER, cre_date TEXT,cre_by TEXT, mod_date TEXT,mod_by TEXT, txn_id INTEGER, delete_ind INTEGER)');
}
static Future<List<Map<String, dynamic>>> query(String table) async =>
_db.query(table);
static Future<int> insert(String table, Model model) async =>
await _db.insert(table, model.toMap());
static Future<Batch> batch() async => _db.batch();
static Future<List<Map<String, dynamic>>> rawQuery(String table) async =>
_db.query(table);
}
You need to store what all values are selected from user and then play with it.
For example -
var selectedIndexes = [];
ListView getNotecheckList() {
return ListView.builder(
itemCount: count,
itemBuilder: (_, int index) {
return Card(
color: Colors.white,
elevation: 2.0,
child: CheckboxListTile(
title: Text(this.noteList[position].note),
subtitle: Text(this.noteList[position].actn_on),
value: selectedIndexes.contains(index),
onChanged: (_) {
if (selectedIndexes.contains(index)) {
selectedIndexes.remove(index); // unselect
} else {
selectedIndexes.add(index); // select
}
},
controlAffinity: ListTileControlAffinity.leading,
),
);
},
);
}
store only index or whole array and play around
Output :-
Code :-
import 'package:flutter/material.dart';
class CheckBoxExample extends StatefulWidget {
const CheckBoxExample({Key? key}) : super(key: key);
#override
State<CheckBoxExample> createState() => _CheckBoxExampleState();
}
class _CheckBoxExampleState extends State<CheckBoxExample> {
List multipleSelected = [];
List checkListItems = [
{
"id": 0,
"value": false,
"title": "Sunday",
},
{
"id": 1,
"value": false,
"title": "Monday",
},
{
"id": 2,
"value": false,
"title": "Tuesday",
},
{
"id": 3,
"value": false,
"title": "Wednesday",
},
{
"id": 4,
"value": false,
"title": "Thursday",
},
{
"id": 5,
"value": false,
"title": "Friday",
},
{
"id": 6,
"value": false,
"title": "Saturday",
},
];
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 64.0),
child: Column(
children: [
Column(
children: List.generate(
checkListItems.length,
(index) => CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
contentPadding: EdgeInsets.zero,
dense: true,
title: Text(
checkListItems[index]["title"],
style: const TextStyle(
fontSize: 16.0,
color: Colors.black,
),
),
value: checkListItems[index]["value"],
onChanged: (value) {
setState(() {
checkListItems[index]["value"] = value;
if (multipleSelected.contains(checkListItems[index])) {
multipleSelected.remove(checkListItems[index]);
} else {
multipleSelected.add(checkListItems[index]);
}
});
},
),
),
),
const SizedBox(height: 64.0),
Text(
multipleSelected.isEmpty ? "" : multipleSelected.toString(),
style: const TextStyle(
fontSize: 22.0,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
],
),
),
);
}
}

How to make a button select all Flutter checkboxes?

The problem is that I cannot make the button select all checkboxes, since I am using an automatically generated list of checkboxes.
Since I created a class with a list item, WordBlock, which is a container with a Checkbox and each checkbox has its own checked value, and therefore I can not select everything in any way. And if I set the checked value through the constructor, then it selects everything, but the onChanged () method does not work and the value of one checkbox does not change. But you need to be able to select the checkboxes one at a time or all at once, select all with the button.
Here is the code for my WordBlock class that appears in the list.
class WordBlock extends StatefulWidget {
final bool checkAll;
WordBlock(this.checkAll);
#override
_WordBlockState createState() => _WordBlockState();
}
class _WordBlockState extends State<WordBlock> {
FlutterTts tts = FlutterTts();
bool checked = false;
Future _speak(String text) async {
await tts.setLanguage('en-US');
await tts.speak(text);
}
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 35.w),
child: Card(
color: checked ? MyColors().scaffoldBG : Colors.white,
elevation: 4.0,
shadowColor: MyColors().black.withOpacity(0.1),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(25.ssp)),
child: CheckboxListTile(
value: checked,
activeColor: MyColors().purple,
onChanged: (value) {
print('changed');
setState(() {
checked = value;
});
},
title: h2(text: 'Car'),
secondary: Padding(
padding: EdgeInsets.only(top: 10.h),
child: InkWell(
onTap: () => _speak('Car'),
child: Icon(
Icons.volume_up_rounded,
color: MyColors().purple,
size: 60.ssp,
),
),
),
subtitle: Text(
'Машина',
style: TextStyle(color: Color(0xFFB8A98BA), fontSize: 27.ssp),
),
),
),
);
}
}
Here is the code for my page that displays the WordBloc list:
class WordPage extends StatefulWidget {
#override
_WordPageState createState() => _WordPageState();
}
class _WordPageState extends State<WordPage> {
bool visible = true;
double banerHeight;
bool checked = false;
#override
void initState() {
super.initState();
}
Widget _wrapWithBanner() {
if (!visible) {
setState(() {
banerHeight = 0;
});
}
return visible
? Container(
margin: EdgeInsets.only(
left: 35.w, right: 35.w, top: 30.h, bottom: 30.h),
padding: EdgeInsets.symmetric(vertical: 25.h),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25.ssp),
color: MyColors().scaffoldBG,
boxShadow: [boxShadow4Y10Blur()]),
child: ListTile(
onTap: () {
print('close');
},
trailing: visible
? InkWell(
onTap: () {
print('tapped');
setState(() {
visible = false;
});
},
child: Icon(Icons.close))
: Container(),
leading: CircleAvatar(),
title: h3bold(text: 'Совет'),
subtitle: Text(
'Чтобы запомнить как можно больше слов, регулярно повторяйте их: каждые два-три часа :)',
style: TextStyle(color: MyColors().black, fontSize: 27.ssp),
),
))
: Container();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: MyColors().white,
appBar: AppBar(
elevation: 2.0,
title: h2(text: 'Работа'),
iconTheme: IconThemeData(size: 20.ssp, color: MyColors().purple),
backgroundColor: MyColors().white,
),
body: Column(
children: [
_wrapWithBanner(),
Row(
children: [
FlatButton( // my selectAll button
onPressed: () {},
child: Row(
children: [
Checkbox(
value: checked,
onChanged: (val) {
setState(() {
checked = val;
});
}),
Text(
'Выделить все',
style: TextStyle(
color: MyColors().purple, fontSize: 27.ssp),
)
],
))
],
),
Expanded(
child: ListView.builder(
itemCount: 4,
itemBuilder: (context, index) {
return WordBlock(checked);
},
))
],
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: Container(
width: 667.w,
height: 91.h,
child: FloatingActionButton(
backgroundColor: MyColors().purple,
onPressed: () {},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24.ssp)),
child: h2reg(
text: "Добавить в мой словарь", textColor: MyColors().white),
),
),
));
}
}
How can this function be implemented?
If you put bool checked = false; in as
class WordBlock extends StatefulWidget {
bool checked = false;
WordBlock();
#override
_WordBlockState createState() => _WordBlockState();
}
You can change it and reach it from _WordBlockState as widget.checked
Checkbox(
value: widget.checked,
onChanged: (val) {
setState(() {
widget.checked = val;
});
}),
it can be modified by both class and not constant.
try below code for with button all checkbox check and uncheck
Output :-
Code :-
import 'package:flutter/material.dart';
class CheckBoxExample extends StatefulWidget {
const CheckBoxExample({Key? key}) : super(key: key);
#override
State<CheckBoxExample> createState() => _CheckBoxExampleState();
}
class _CheckBoxExampleState extends State<CheckBoxExample> {
List multipleSelected = [];
List checkListItems = [
{
"id": 0,
"value": false,
"title": "Sunday",
},
{
"id": 1,
"value": false,
"title": "Monday",
},
{
"id": 2,
"value": false,
"title": "Tuesday",
},
{
"id": 3,
"value": false,
"title": "Wednesday",
},
{
"id": 4,
"value": false,
"title": "Thursday",
},
{
"id": 5,
"value": false,
"title": "Friday",
},
{
"id": 6,
"value": false,
"title": "Saturday",
},
];
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 64.0),
child: Column(
children: [
InkWell(
onTap: () => setState(() {
multipleSelected.clear();
for (var element in checkListItems) {
if (element["value"] == false) {
element["value"] = true;
multipleSelected.add(element);
} else {
element["value"] = false;
multipleSelected.remove(element);
}
}
}),
child: const Text(
"Select All",
style: TextStyle(
fontSize: 22.0,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
Column(
children: List.generate(
checkListItems.length,
(index) => CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
contentPadding: EdgeInsets.zero,
dense: true,
title: Text(
checkListItems[index]["title"],
style: const TextStyle(
fontSize: 16.0,
color: Colors.black,
),
),
value: checkListItems[index]["value"],
onChanged: (value) {
setState(() {
checkListItems[index]["value"] = value;
});
},
),
),
),
Text(
multipleSelected.isEmpty ? "" : multipleSelected.toString(),
style: const TextStyle(
fontSize: 22.0,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
],
),
),
);
}
}