I would like to ask for your help with this, please.
My sample code below aims to update the State of the Parent Widget from the Child Widget while also updating the Child Widget's State. The text value of the Parent Widget would update while also changing the color of the Child Widget's button.
import 'package:flutter/material.dart';
void main() => runApp(AppIndex());
class AppIndex extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: ParentWidget());
}
}
class ParentWidget extends StatefulWidget {
@override
_ParentWidgetState createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
String _textValue = 'Old Value';
callback(newValue){
setState(() {
_textValue = newValue;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Text(_textValue),
ChildWidget(),
],
);
}
}
class ChildWidget extends StatefulWidget {
String textValue;
Function callback;
ChildWidget({this.textValue, this.callback});
@override
_ChildWidgetState createState() => _ChildWidgetState();
}
class _ChildWidgetState extends State<ChildWidget> {
bool buttonState = false;
@override
Widget build(BuildContext context) {
return RaisedButton(
color: buttonState == true ? Colors.greenAccent : Colors.redAccent,
child: Text('Update State'),
onPressed: () {
setState(() {
if (buttonState == false) {
buttonState = true;
} else if (buttonState == true) {
buttonState = false;
}
});
widget.callback('New Value');
},
);
}
}
So far, what this is able to do is to update the color/state of the Child Widget, however, the Parent Widget doesn't seem to update its State. My original code, which this was take from, actually only updates the the Parent's State only but not both Parent and Child (same concept and concern).
The sample code above are derivatives of the results of my initial research before asking here.
I'm thinking there must be something wrong with how I structure my code or this is not possible with Flutter's Architecture based on how I made it. If possible, can you give me your recommendations for something with the same behavior? (Updating the Parent and Child States)
Sorry I am new to this type of programming and architecture.