Reputation: 214
Problem:
I have a parent widget SnippetTestEditor
and a stateful child widget NoteTab
. If a button in the parent widget is pressed, the child widget should get updated.
Both classes have a bool _editMode
. I pass the bool from the parent widget to the child widget via the constructor. From my understandig, I need to call setState()
in the parent widget and change the bool within setState()
. This change should automatically be reflected in the child widget. But it's not....
So how can I get the child widget to change?
Code:
class _SnippetTestEditorState extends State<SnippetTestEditor> with SingleTickerProviderStateMixin {
bool _editMode = true;
...
@override
void initState() {
super.initState();
_tabs = List();
_tabNames = List();
List<CodeSnippet> codeSnippets = this.widget._note.codeSnippets;
for(CodeSnippet snippet in codeSnippets){
_tabs.add(CodeTab(_editMode);
...
}
@override
Widget build(BuildContext context) {
return Scaffold(
...
body: TabBarView(
controller: _tabController,
children: _tabs
),
...
actions: <Widget>[
IconButton(
icon: Icon(Icons.check),
onPressed: (){
setState(() {
_editMode = false;
});
},
)
...
class CodeTab extends StatefulWidget{
bool _editMode;
CodeTab(this._editMode);
@override
State<StatefulWidget> createState() => CodeTabState();
}
class CodeTabState extends State<CodeTab> {
@override
Widget build(BuildContext context) {
return this.widget._editMode ? ...
Upvotes: 0
Views: 3840
Reputation: 3193
This happens because _editMode
value is passed to CodeTab
only once, inside initState()
. So, even though the build
method is called multiple times, the CodeTab
instances in _tabs
do not get updated.
you should move the code to create tabs in a method inside the state class:
getTabs(){
List<CodeSnippet> codeSnippets = widget._note.codeSnippets;
for(CodeSnippet snippet in codeSnippets){
_tabs.add(CodeTab(_editMode);
return _tabs;
}
and use getTabs()
in build:
body: TabBarView(
controller: _tabController,
children: getTabs(),
),
If you have any doubts in this solution, Let me know in the comments.
Upvotes: 3