Reputation: 1218
I don't understand why in flutter is not possible to have a structure like this:
//...
Scaffold(
//...
body: myPage(dataList[index])
)
//...
Where myPage is a class that extends statefulWidget and returns a ListView. It requires a data parameter that is stored in an array. I want to change the body of my scaffold when I change the index for example with a navigation drawer.
I noticed that:
And Yes, I used the setState method to refresh the layout whenever I change the index.
Is this a bug or I missed something? If it is not a bug, what could I do as workaround? Thanks in advance
UPDATE:
I post the code of another page that is simpler with nothing strange where there is anyway this problem (I know in this page I could use a statelessWidget but it should work anyway):
class FirstFragment extends StatefulWidget {
String data;
FirstFragment(this.data);
@override
_FirstFragment createState() => new _FirstFragment(data);
}
class _FirstFragment extends State<FirstFragment>{
String data;
_FirstFragment(this.data);
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Center(
child: new Text(data),
);
}
}
Upvotes: 1
Views: 1915
Reputation: 472
You shouldn't pass parameters from parent widget class to its state - you can access them thru "widget" directive. Also, listen to Lint - all instances should be final in the main class.
class FirstFragment extends StatefulWidget {
final String data;
FirstFragment(this.data);
@override
_FirstFragment createState() => new _FirstFragment();
}
class _FirstFragment extends State<FirstFragment>{
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Center(
child: new Text(widget.data),
);
}
}
Upvotes: 2