I’m new to Flutter and I’ve been trying to create a simple utility in my app with a few input fields that are disabled until the “Edit” button is clicked. Once it is clicked all the fields become editable.
When the “Edit” button is clicked it shows additional widgets. There is an “Add” button that adds the device widget (child) to the parent widget.
I’m updating the value of the _isEditing
variable on the click of the Edit button but it is not changing the state of the child variable which I’m passing through the constructor. I’m having a hard time understanding this. Please help me out, how can I update the state of the child class as well?
Here, is the code for the Parent class
class Parent extends StatefulWidget {
final int index;
const Parent({super.key, required this.index});
@override
State<Parent> createState() => _ParentState();
}
class _ParentState extends State<ParentBox> {
bool _isEditing = false;
List _devices = [];
@override
void initState() {
super.initState();
_devices.add(Child(isEditing: _isEditing, index: 0));
}
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Container(
child: Column(
children: [
formField(
"Location:",
TextEditingController(),
hint: "Enter location",
small: true,
required: false,
labelSize: 16,
disabled: !_isEditing
),
SizedBox(height: 10),
..._devices,
SizedBox(height: 10,),
_isEditing
? Align(
child: SizedBox(
height: 30,
child: generalButton("+ Add", onPressed: (){
setState(() {
_devices.add(Child(isEditing: _isEditing, index: _devices.length - 1));
});
}),
)
)
: Container(),
SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
InkWell(
onTap: () {
showAlertDialog(
context,
"Alert",
"Alert text"
onYesPressed: () {
},
);
},
child: Icon(
Icons.delete_outline_rounded,
color: Colors.red,
),
),
_isEditing
? generalButton("Save", onPressed: () {
setState(() {
_isEditing = !_isEditing;
});
})
: generalButton("Edit", onPressed: () {
setState(() {
_isEditing = !_isEditing;
});
})
],
),
],
),
),
SizedBox(height: 30),
],
),
);
}
}
Here is the code for the child class
class Child extends StatelessWidget {
final bool isEditing;
final int index;
const Child({super.key, required this.isEditing, required this.index});
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
width: MediaQuery.of(context).size.width * 0.4,
child: formField(
"Device:",
TextEditingController(),
small: true,
required: false,
labelSize: 16,
disabled: !isEditing
),
),
SizedBox(
width: MediaQuery.of(context).size.width * 0.4,
child: formField(
"Expiration Date:",
TextEditingController(),
small: true,
required: false,
labelSize: 16,
disabled: !isEditing
),
),
],
);
}
}
I would appreciate any help. Thanks!