Passing Data to a Stateful Widget in Flutter

Don’t pass parameters to State using it’s constructor.
You should only access the parameters using this.widget.myField.

Not only editing the constructor requires a lot of manual work ; it doesn’t bring anything. There’s no reason to duplicate all the fields of Widget.

EDIT :

Here’s an example:

class ServerIpText extends StatefulWidget {
  final String serverIP;

  const ServerIpText ({ Key? key, this.serverIP }): super(key: key);

  @override
  _ServerIpTextState createState() => _ServerIpTextState();
}

class _ServerIpTextState extends State<ServerIpText> {
  @override
  Widget build(BuildContext context) {
    return Text(widget.serverIP);
  }
}

class AnotherClass extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: ServerIpText(serverIP: "127.0.0.1")
    );
  }
}

Leave a Comment