Flutter/Dart: Pass Parameters to a Stateful Widget?
Solution 1
Looks like the solution was to separate the title from the oldtitle;
class EditPage extends StatefulWidget {
String oldtitle;
EditPage({this.oldtitle})
and then;
class _EditPageState extends State<EditPage> {
String title;
So now for the form;
Container(
child: TextField(
decoration: new InputDecoration(
hintText: widget.oldtitle,
contentPadding: new EdgeInsets.all(1.0),
border: InputBorder.none,
filled: true,
fillColor: Colors.grey[300],
),
keyboardType: TextInputType.text,
autocorrect: false,
onChanged: (titleText) {
setState(() {
title= titleText;
});
},
),
),
Solution 2
You should never pass the variables to the state directly, since it does not guarantee that widget will get rebuilt when state will be updated. You should accept parameters via your stateful widget and access them from the state itself via widget.variable
.
Example:
class TestWidget extends StatefulWidget {
final String variable;
TestWidget({Key key, @required this.variable}) : super(key: key);
@override
_TestWidgetState createState() => _TestWidgetState();
}
class _TestWidgetState extends State<TestWidget> {
@override
Widget build(BuildContext context) {
return Container(
child: Center(
// Accessing the variables passed into the StatefulWidget.
child: Text(widget.variable),
),
);
}
}
Meggy
I'm a self-taught novice stumbling like a drunk through php, javascript, mysql, drupal and flutter.
Updated on December 23, 2022Comments
-
Meggy over 1 year
I need to call pass my
title
andoldtitle
parameters to myEditPage
Stateful widget. But if I do this;class EditPage extends StatefulWidget { String title; String oldtitle; EditPage({this.title, this.oldtitle})
The strings are not available to the build unless I call it them as
widget.title
andwidget.oldtitle
.But I'm using a
textfield
within a form that doesn't seem to work right if I use these widgets.Here's the form code:
Container( child: TextField( decoration: new InputDecoration( hintText: widget.oldtitle, contentPadding: new EdgeInsets.all(1.0), border: InputBorder.none, filled: true, fillColor: Colors.grey[300], ), keyboardType: TextInputType.text, autocorrect: false, onChanged: (titleText) { setState(() { widget.title= titleText; }); }, ), ),
But then if I do this;
class _EditPageState extends State<EditPage> { String title; String oldtitle; EditPage({this.title, this.oldtitle})
I can't pass the title parameter to it from another screen. IE:
`EditPage(title:mytitle, oldtitle:myoldtitle);`
So What's the correct way to pass a parameter to a Stateful widget?
-
Meggy over 3 yearsIf that's the case I'm guessing my problem is with the form and not with the passing of parameters. I tried your code and still, my form is not working. I'll edit to include the code for the form;
-
nikoss almost 2 yearsthis doesnt really seem to work any more. Error says variable cannot be null