Not being able to pass bool value - flutter

I am getting error while trying to pass bool value to the TaskCheckbox() method. I am new to flutter and any help would be much appreciated
class _TaskTileState extends State<TaskTile> {
bool? isChecked = false;
#override
Widget build(BuildContext context) {
return const ListTile(
title: Text('This is a task'),
trailing: TaskCheckbox(isChecked),
);
}
}
class TaskCheckbox extends StatelessWidget {
final bool? checkboxState;
const TaskCheckbox(this.checkboxState, {Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Checkbox(
value: checkboxState,
onChanged: (newValue) {},
);
}
}

You need to remove const before ListTile because the value will get on runtime.
#override
Widget build(BuildContext context) {
return ListTile(
title: Text('This is a task'),
trailing: TaskCheckbox(isChecked),
);
}
const keyword used to make a variable to store a compile time constant value. Compile time constant value is a value which will be constant while compiling , ref

You need to use Stateful Class widget for the build checkbox because we need to use setState for changing value inside the checkbox.
Use this code. This work fine for me:
class TaskTileState extends StatefulWidget {
#override
_TaskTileState createState() => _TaskTileState();
}
class _TaskTileState extends State<MyHomePage> {
bool? isChecked = true;
#override
Widget build(BuildContext context) {
return ListTile(
title: Text('This is a task'),
trailing: TaskCheckbox(isChecked),
);
}
}
class TaskCheckbox extends StatefulWidget {
final bool? checkboxState;
const TaskCheckbox(this.checkboxState, {Key? key}) : super(key: key);
#override
State<TaskCheckbox> createState() => _TaskCheckboxState();
}
class _TaskCheckboxState extends State<TaskCheckbox> {
bool? isChecked;
#override
void initState() {
isChecked = widget.checkboxState;
}
#override
Widget build(BuildContext context) {
Color getColor(Set<MaterialState> states) {
const Set<MaterialState> interactiveStates = <MaterialState>{
MaterialState.pressed,
MaterialState.hovered,
MaterialState.focused,
};
if (states.any(interactiveStates.contains)) {
return Colors.blue;
}
return Colors.red;
}
return Checkbox(
checkColor: Colors.black,
fillColor: MaterialStateProperty.resolveWith(getColor),
value: isChecked,
onChanged: (bool? value) {
setState(() {
isChecked = value!;
});
},
);
}
}
Related from #Yeasin Sheikh's answer, you do have to remove the const in the ListView

Related

Flutter lifting the state up through multiple dynamically added widgets

I'm trying to build a parent widget that has a button, when clicked, it displays another widget with some text and a drop-down list. When the drop-down selection is changed, the text should change accordingly. I've included below a simplified code of what I'm trying to achieve which doesn't work. The state lifting up concept is something confusing for me as a newcomer to Flutter
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String text = "Empty";
void addWidget() {
setState(() {
widList.clear();
widList.add(MidWidget(
text: text,
setValue: selectValue,
));
});
}
void selectValue(String value) {
setState(() {
text = value;
});
}
List<Widget> widList = [];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(children: [
ElevatedButton(onPressed: addWidget, child: const Text("Add Widget")),
Column(
children: widList,
)
]),
),
);
}
}
class MidWidget extends StatelessWidget {
const MidWidget({super.key, required this.text, required this.setValue});
final String text;
final Function setValue;
#override
Widget build(BuildContext context) {
return Column(
children: [
Text(text),
LowestWidget(
dropDownValue: "First",
setValue: setValue,
),
],
);
}
}
////////////////////
///////////////////
///
class LowestWidget extends StatelessWidget {
LowestWidget(
{super.key, required this.dropDownValue, required this.setValue});
final List<String> items = ["First", "Second"];
final String dropDownValue;
final Function setValue;
#override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: dropDownValue,
icon: const Icon(Icons.arrow_downward),
onChanged: (String? value) {
setValue(value);
},
items: items.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
);
}
}
First of all, both MidWidget and LowestWidget need to be converted to StatefulWidget because we need state changes inside those widgets too.
Secondly, selectValue function should be in the MidWidget, not in the parent widget, because it attempts to change the state of text that has already been passed onto the MidWidget with its original value at the time of its instantiation. Any change in text via setState is not going to affect its value in MidWidget anymore.
Thirdly, I've introduced _value variable in both MidWidget and LowestWidget that takes its initial value from the respective parent widgets in initState and then gets value changes via setState that are then used to be displayed in Text widget in MidWidget and DropdownButton widget in LowestWidget.
Following is the revised code that is working as per your requirements. I've commented out the deletions so that you could relate it with the original code.
Hope it helps!
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String text = "Empty";
void addWidget() {
setState(() {
widList.clear();
widList.add(MidWidget(
text: text,
// setValue: selectValue,
));
});
}
// void selectValue(String value) {
// setState(() {
// text = value;
// });
// }
List<Widget> widList = [];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(children: [
ElevatedButton(onPressed: addWidget, child: const Text("Add Widget")),
Column(
children: widList,
)
]),
),
);
}
}
class MidWidget extends StatefulWidget {
const MidWidget({super.key, required this.text, /*required this.setValue*/});
final String text;
// final Function setValue;
#override
State<MidWidget> createState() => _MidWidgetState();
}
class _MidWidgetState extends State<MidWidget> {
String? _value;
void selectValue(String value) {
setState(() => _value = value);
}
#override
void initState() {
_value = widget.text;
super.initState();
}
#override
Widget build(BuildContext context) {
return Column(
children: [
Text(_value!),
LowestWidget(
dropDownValue: "First",
setValue: selectValue,
),
],
);
}
}
////////////////////
///////////////////
///
class LowestWidget extends StatefulWidget {
LowestWidget(
{super.key, required this.dropDownValue, required this.setValue});
final String dropDownValue;
final Function setValue;
#override
State<LowestWidget> createState() => _LowestWidgetState();
}
class _LowestWidgetState extends State<LowestWidget> {
final List<String> items = ["First", "Second"];
String? _value;
#override
void initState() {
_value = widget.dropDownValue;
super.initState();
}
#override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: _value,
icon: const Icon(Icons.arrow_downward),
onChanged: (String? value) {
setState(() => _value = value);
widget.setValue(value);
},
items: items.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
);
}
}

how to disable button in Flutter 3.3.4

in Flutter 3.3.4 , I want control the state of the button by passing an object with its properties
. I tried some solutions in stackoverflow (e.g How do I disable a Button in Flutter? ),but failed。
I print the flag of the object , it looks right.
here is my code
// Copyright 2018 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
SwitchWidget wifiSwitch = SwitchWidget();
// SwitchWidget timeSwitch = SwitchWidget();
// SwitchWidget locationSwitch = SwitchWidget();
return MaterialApp(
title: 'Startup N1ame Generator',
home: Scaffold(
appBar: AppBar(
title: const Text('Startup Name Generator'),
),
body: Center(
child: Row(
children: [
Column(children: [wifiSwitch]),
Column(children: [ButtonWidget(wifiSwitch)])
],
),
),
),
);
}
}
class SwitchWidget extends StatefulWidget {
bool flag = true;
SwitchWidget({Key? key}) : super(key: key);
#override
State<SwitchWidget> createState() => _SwitchWidgetState(this);
}
class _SwitchWidgetState extends State<SwitchWidget> {
SwitchWidget switchWidget;
_SwitchWidgetState(this.switchWidget);
#override
Widget build(BuildContext context) {
return Container(
child: Switch(
value: switchWidget.flag,
onChanged: (newValue) => {
setState(() {
switchWidget.flag = newValue;
print("-----------${switchWidget.flag}");
})
},
),
);
}
}
class ButtonWidget extends StatefulWidget {
late SwitchWidget _switchWidget;
SwitchWidget get switchWidget => _switchWidget;
set switchWidget(SwitchWidget switchWidget) => {
print('The ButtonWidget is $switchWidget.'),
_switchWidget = switchWidget
};
ButtonWidget(switchWidget, {Key? key}) : super(key: key) {
this.switchWidget = switchWidget;
}
#override
State<ButtonWidget> createState() => _ButtonWidgetState(switchWidget);
}
class _ButtonWidgetState extends State<ButtonWidget> {
SwitchWidget switchWidget;
_ButtonWidgetState(this.switchWidget);
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.fromLTRB(50, 1, 1, 1),
child: ElevatedButton(
// color: Colors.blue,
// disabledColor: Colors.grey,
// textColor: Colors.black,
child: Text("123"),
// onPressed: () {},
onPressed: this.switchWidget.flag ? _incrementCounter : null,
style: ButtonStyle(
foregroundColor: MaterialStateProperty.resolveWith(
(states) {
if (states.contains(MaterialState.disabled)) {
return Colors.grey;
} else {
return Colors.white;
}
},
),
)),
);
{}
}
void _incrementCounter() {
print("object******** ${this.switchWidget.flag}");
}
}
Why do you pass a reference of SwitchWidget to _SwitchWidgetState? You should move the property bool flag = true; to _SwitchWidgetState and then change it directly in setState(() => flag = newValue);.
Also, your ButtonWidget is not rebuilt on change in SwitchWidget. You'll have to use some sort of state management in order to disable the button on a state change of your switch widget.
For example using callbacks:
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_svg/flutter_svg.dart';
class ParentWidget extends StatefulWidget {
const ParentWidget({super.key});
#override
State<ParentWidget> createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
bool _isDisabled = false;
#override
Widget build(BuildContext context) {
return Column(
children: [
SwitchWidget(initialValue: true, onChanged: (val) => setState(() => _isDisabled = val)),
ButtonWidget(isDisabled: _isDisabled),
],
);
}
}
class SwitchWidget extends StatefulWidget {
final bool initialValue;
final void Function(bool) onChanged;
const SwitchWidget({super.key, required this.onChanged, required this.initialValue});
#override
State<SwitchWidget> createState() => _SwitchWidgetState();
}
class _SwitchWidgetState extends State<SwitchWidget> {
late bool _value;
#override
void initState() {
super.initState();
_value = widget.initialValue;
}
#override
Widget build(BuildContext context) {
return Switch(
value: _value,
onChanged: (val) {
setState(() => _value = val);
widget.onChanged(val);
},
);
}
}
class ButtonWidget extends StatelessWidget {
final bool isDisabled;
const ButtonWidget({super.key, required this.isDisabled});
#override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: isDisabled
? null
: () {
//Some logic
},
child: Text("Press me!"),
);
}
}
You can pass null where you place your function, or even some of Flutter's Widgets already have the enabled property. But setState and change the function to null and you should get what you want.

Is there a way I can have my HookWidget rebuild when the text of the TextEditingController changes?

I have a test edit field. When there is no text, I want a button disabled. When there is text in the TextField, I want the button enabled.
I am using flutter_hooks to reduce boiler plate code for controllers.
In the following example, when I enter test into the text field, the button never enables, because build is not triggered? How can I trigger a build when using a text editing controller with flutter hooks?
class MyHomePage extends HookWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
var ctrl = useTextEditingController();
VoidCallback? onPressed;
if (ctrl.text.isNotEmpty) {
onPressed = () => print("Pressed!");
}
return Scaffold(
body: Column(
children: [
TextField(
controller: ctrl,
),
ElevatedButton(onPressed: onPressed, child: Text("Button")),
],
)
);
}
}
You can Achieve this using useState and useTextEditingController
var istextchanged = useState<bool>(false);
ctrl.addListener(() {
if (ctrl.text.isEmpty) {
istextchanged.value = false;
} else {
istextchanged.value = true;
}
});
Yourwidget
class MyHomePages2 extends HookWidget {
const MyHomePages2({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
var ctrl = useTextEditingController();
var istextchanged = useState<bool>(false);
ctrl.addListener(() {
if (ctrl.text.isEmpty) {
istextchanged.value = false;
} else {
istextchanged.value = true;
}
});
VoidCallback? onPressed = () {
print("change");
};
if (ctrl.text.isNotEmpty) {
onPressed = () => print("Pressed!");
}
return Scaffold(
body: Column(
children: [
TextField(
controller: ctrl,
onChanged: (v) {},
),
ElevatedButton(
onPressed: istextchanged.value ? onPressed : null,
child: Text("Button"))
],
));
}
}
Package used flutter_hooks: ^0.18.2+1
pub.dev/flutter_hooks
SampleCode
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
int myvalue = 0;
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
#override
void initState() {
// functions().then((int value) {
// setState(() {
// myvalue = value;
// });
// future is completed you can perform your task
// });
}
Future<int> functions() async {
// do something here
return Future.value();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: MyHomePages2(),
);
}
}
class MyHomePages2 extends HookWidget {
const MyHomePages2({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
var ctrl = useTextEditingController();
var istextchanged = useState<bool>(false);
ctrl.addListener(() {
if (ctrl.text.isEmpty) {
istextchanged.value = false;
} else {
istextchanged.value = true;
}
});
VoidCallback? onPressed = () {
print("change");
};
if (ctrl.text.isNotEmpty) {
onPressed = () => print("Pressed!");
}
return Scaffold(
body: Column(
children: [
TextField(
controller: ctrl,
onChanged: (v) {},
),
ElevatedButton(
onPressed: istextchanged.value ? onPressed : null,
child: Text("Button"))
],
));
}
}

setState() method doesn't update the widget

it is not updating my widget. If I click on the switch to turn _darkMode on the switch is always moving back (doesn't change)...
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class SettingsScreen extends StatefulWidget {
const SettingsScreen({Key? key}) : super(key: key);
#override
_SettingsScreenState createState() => _SettingsScreenState();
}
class _SettingsScreenState extends State<SettingsScreen> {
#override
Widget build(BuildContext context) {
bool _darkMode = false;
return Container(
child: ListView(
children: [
ListTile(
title: const Text('Lights'),
trailing: CupertinoSwitch(
value: _darkMode,
onChanged: (bool value) {
setState(() {
_darkMode = value;
print('DarkMode: $_darkMode');
});
},
),
),
],
));
}
}
_darkMode must be a field in the widget state. Move it outside the build method:
class _SettingsScreenState extends State<SettingsScreen> {
bool _darkMode = false;
#override
Widget build(BuildContext context) {

The argument type 'Function' can't be assigned to the parameter type 'void Function(bool?)?'

I am trying to pass a function using constructor arguments but it shows me the error mentioned in the title.
import 'package:flutter/material.dart';
class TaskTile extends StatefulWidget {
#override
_TaskTileState createState() => _TaskTileState();
}
class _TaskTileState extends State<TaskTile> {
bool isChecked = false;
#override
Widget build(BuildContext context) {
return ListTile(
title: Text(
'This is a task',
style: TextStyle(
decoration: isChecked ? TextDecoration.lineThrough : null,
),
),
trailing: TaskCheckbox(
checkboxState: isChecked,
toggleCheckboxState: (bool checkboxState) {
setState(() {
isChecked = checkboxState;
});
},
),
);
}
}
class TaskCheckbox extends StatelessWidget {
final bool checkboxState;
final Function toggleCheckboxState;
TaskCheckbox(
{required this.checkboxState, required this.toggleCheckboxState});
#override
Widget build(BuildContext context) {
return Checkbox(
activeColor: Colors.lightBlueAccent,
value: checkboxState,
onChanged: toggleCheckboxState,
);
}
}
I searched the web for this but no luck over there.
so if anybody could help me out would me much appriciated.
Your final Function toggleCheckboxState; needs to have a bool? parameter.
Try like this:
final Function(bool?) toggleCheckboxState;
You also need to change the code while assigning toggleCheckboxState like this,
toggleCheckboxState: (bool? checkboxState) {
setState(() {
isChecked = checkboxState!;
});
},
bool? checkboxState would be required here since your type is Function(bool?)
`import 'dart:ui';
import 'package:flutter/material.dart';
class TaskTile extends StatefulWidget {
#override
_TaskTileState createState() => _TaskTileState();
}
class _TaskTileState extends State<TaskTile> {
bool isChecked = false;
checkBoxCallback(bool checkBoxState) {
setState(() {
isChecked = checkBoxState;
});
}
#override
Widget build(BuildContext context) {
return ListTile(
title: Text(
"Complete Assignments",
style: TextStyle(
decoration: isChecked ? TextDecoration.lineThrough : null,
fontSize: 20,
),
),
trailing: TaskCheckbox(
checkBoxState: isChecked, toggleCheckBoxState: checkBoxCallback), );
}
}
class TaskCheckbox extends StatelessWidget {
final bool checkBoxState;
final Function toggleCheckBoxState;
const TaskCheckbox(
{Key? key,
required this.checkBoxState,
required this.toggleCheckBoxState})
: super(key: key);
#override
Widget build(BuildContext context) {
return Checkbox(
activeColor: Colors.blue,
value: checkBoxState,
onChanged: (newValue) {
toggleCheckBoxState(newValue);
});
}
}
'I am convinced that you were looking at the course of Anjela Yu and me too I found the solution'#the keyword is down-casting about null safety
import 'package:flutter/material.dart';
class TaskTile extends StatefulWidget {
#override
_TaskTileState createState() => _TaskTileState();
}
class _TaskTileState extends State<TaskTile> {
bool isChecked = false;
#override
Widget build(BuildContext context) {
return ListTile(
title: Text(
'This is a task',
style: TextStyle(
decoration: isChecked ? TextDecoration.lineThrough : null,
),
),
trailing: TaskCheckbox(
checkboxState: isChecked,
toggleCheckboxState: (bool? checkboxState) {
setState(() {
isChecked = checkboxState!;
});
},
),
);
}
}
class TaskCheckbox extends StatelessWidget {
final bool checkboxState;
final Function? toggleCheckboxState;
TaskCheckbox(
{required this.checkboxState, required this.toggleCheckboxState});
#override
Widget build(BuildContext context) {
return Checkbox(
activeColor: Colors.lightBlueAccent,
value: checkboxState,
onChanged: toggleCheckboxState as void Function(bool?)?
);
}
}
Faced the same issue, below is an example of code I like using.
For more information check the documentation: Checkbox class
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: MyStatefulWidget(),
),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool isChecked = false;
#override
Widget build(BuildContext context) {
Color getColor(Set<MaterialState> states) {
const Set<MaterialState> interactiveStates = <MaterialState>{
MaterialState.pressed,
MaterialState.hovered,
MaterialState.focused,
};
if (states.any(interactiveStates.contains)) {
return Colors.blue;
}
return Colors.red;
}
return Checkbox(
checkColor: Colors.white,
fillColor: MaterialStateProperty.resolveWith(getColor),
value: isChecked,
onChanged: (bool? value) {
setState(() {
isChecked = value!;
});
},
);
}
}