302

I'm wondering what the recommended way of passing data to a stateful widget, while creating it, is.

The two styles I've seen are:

class ServerInfo extends StatefulWidget {

  Server _server;

  ServerInfo(Server server) {
    this._server = server;
  }

  @override
    State<StatefulWidget> createState() => new _ServerInfoState(_server);
}

class _ServerInfoState extends State<ServerInfo> {
  Server _server;

  _ServerInfoState(Server server) {
    this._server = server;
  }
}

This method keeps a value both in ServerInfo and _ServerInfoState, which seems a bit wasteful.

The other method is to use widget._server:

class ServerInfo extends StatefulWidget {

  Server _server;

  ServerInfo(Server server) {
    this._server = server;
  }

  @override
    State<StatefulWidget> createState() => new _ServerInfoState();
}

class _ServerInfoState extends State<ServerInfo> {
  @override
    Widget build(BuildContext context) {
      widget._server = "10"; // Do something we the server value
      return null;
    }
}

This seems a bit backwards as the state is no longer stored in _ServerInfoSate but instead in the widget.

Is there a best practice for this?

5

9 Answers 9

547

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")
    );
  }
}
Sign up to request clarification or add additional context in comments.

16 Comments

A further comment, anything you pass to a State object through the constructor won't ever get updated!
And here I am and don't understand the comment. "Don't pass parameters to State using it's constructor". So how do I pass parameters to the State?
@Rexford State already as access to all the properties of Stateful by using the widget field.
@RémiRousselet What if I want to use foo to pre-fill a textfield, and still allow the user to edit it. Should I also add another foo property in the state?
On other hand, keeping all the objects in widget instead of state seems weird.
|
72

Best way is don't pass parameters to State class using it's constructor. You can easily access in State class using widget.myField.

For Example

class UserData extends StatefulWidget {
  final String clientName;
  final int clientID;
  const UserData(this.clientName,this.clientID);

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

class UserDataState extends State<UserData> {
  @override
  Widget build(BuildContext context) {
    // Here you direct access using widget
    return Text(widget.clientName); 
  }
}

Pass your data when you Navigate screen :

 Navigator.of(context).push(MaterialPageRoute(builder: (context) => UserData("WonderClientName",132)));

Comments

22

Another answer, building on @RémiRousselet's anwser and for @user6638204's question, if you want to pass initial values and still be able to update them in the state later:

class MyStateful extends StatefulWidget {
  final String foo;

  const MyStateful({Key key, this.foo}): super(key: key);

  @override
  _MyStatefulState createState() => _MyStatefulState(foo: this.foo);
}

class _MyStatefulState extends State<MyStateful> {
  String foo;

  _MyStatefulState({this.foo});

  @override
  Widget build(BuildContext context) {
    return Text(foo);
  }
}

7 Comments

We can directly use initState to do something like foo = widget.foo, no passing to constructor is required
How to pass argument to this ?
@SteevJames the widget MyStateful has one optional named parameter (property) you can create this widget by calling MyStateful(foo: "my string",)
@Aqib the initState does not solve a problem in the following scenario: for example, you created your Statefull widget with empty parameters and you're waiting for your data to load. When the data is loaded you want to update your Statefull widget with the fresh data and in this case when you call MyStatefull(newData) it's initState() won't be called! In this case didUpdateWidget(MyStatefull oldWidget) will be called and you would need to compare your data from argument oldWidget.getData() with widget.data and if it's not the same - call setState() to rebuild the widget.
@kirill-karmazin can you elaborate more on the Stateless widget solution? what would you use instead? Is it a best practice from the Flutter team? Thank you
|
21

For passing initial values (without passing anything to the constructor)

class MyStateful extends StatefulWidget {
  final String foo;

  const MyStateful({Key key, this.foo}): super(key: key);

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

class _MyStatefulState extends State<MyStateful> {
  @override
  void initState(){
    super.initState();
    // you can use this.widget.foo here
  }

  @override
  Widget build(BuildContext context) {
    return Text(foo);
  }
}

1 Comment

you can use this.widget.foo here very underrated info. thanks for the tip
5

Flutter's stateful widgets API is kinda awkward: storing data in Widget in order to access it in build() method which resides in State object 🤦 If you don't want to use some of bigger state management options (Provider, BLoC), use flutter_hooks (https://pub.dev/packages/flutter_hooks) - it is a nicer and cleaner substitute for SatefullWidgets:

class Counter extends HookWidget {
  final int _initialCount;

  Counter(this._initialCount = 0);
  
  @override
  Widget build(BuildContext context) {
    final counter = useState(_initialCount);

    return GestureDetector(
      // automatically triggers a rebuild of Counter widget
      onTap: () => counter.value++,
      child: Text(counter.value.toString()),
    );
  }
}

Comments

3

The best practice is to define the stateful widget class as immutable which means defining all dependencies (arrival parameter) as final parameters. and getting access to them by widget.<fieldName> in the state class. In case you want to change their values like reassigning you should define the same typed properties in your state class and re-assign them in the initState function. it is highly recommended not to define any not-final property in your stateful widget class and make it a mutable class. something like this pattern:

class SomePage extends StatefulWidget{
  final String? value;
  SomePage({this.value});

  @override
  State<SomePage> createState() => _SomePageState();
}

class _SomePageState extends State<SomePage> {
  String? _value;

  @override
  void initState(){
    super.initState();
    setState(() {
      _value = widget.value;
    });
  }

 @override
 Widget build(BuildContext context) {
    return Text(_value);
 }
}

1 Comment

It is not correct to use setState() within initState(). setState() should only be used when you update the state later: stackoverflow.com/questions/53363774/…
1

@Rémi Rousselet, @Sanjayrajsinh, @Daksh Shah is also better. but I am also defined this is in from starting point.that which parameter is which value

   import 'package:flutter/material.dart';
    
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      String name = "Flutter Demo";
      String description = "This is Demo Application";
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: MainActivity(
            appName: name,
            appDescription: description,
          ),
        );
      }
    }
    
    class MainActivity extends StatefulWidget {
      MainActivity({Key key, this.appName, this.appDescription}) : super(key: key);
      var appName;
      var appDescription;
    
      @override
      _MainActivityState createState() => _MainActivityState();
    }
    
    class _MainActivityState extends State<MainActivity> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.appName),
          ),
          body: Scaffold(
            body: Center(
              child: Text(widget.appDescription),
            ),
          ),
        );
      }
    }

Comments

0

If you need to pass parameters directly to a StatefulWidget, there are two ways to do it, depending on whether you need the parameter to be final or not in the State.

If the parameter is final we can declare it directly in the StatefulWidget and call it from the State using the "widget" prefix:

class ServerInfo extends StatefulWidget {
  final Server server;

  const ServerInfo({super.key, required this.server});

  @override
  State<ServerInfo> createState() => _ServerInfoState();
}

class _ServerInfoState extends State<ServerInfo> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(widget.server.name),
    );
  }
}

If you need to create a variable based on the original parameter then, you must create a variable in the State that obtains the value from the original parameter using "initState":

class ServerInfo extends StatefulWidget {
  final Server server;

  const ServerInfo({super.key, required this.server});

  @override
  State<ServerInfo> createState() => _ServerInfoState();
}

class _ServerInfoState extends State<ServerInfo> {
  late Server _server;

  @override
  void initState() {
    _server = widget.server;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(_server.name),
    );
  }
}

It is bad practice to pass logic through the State, this is an example of this practice and we should avoid it:

class ServerInfo extends StatefulWidget {
  final Server server;

  const ServerInfo({super.key, required this.server});

  @override
  State<ServerInfo> createState() => _ServerInfoState(server: server);
}

class _ServerInfoState extends State<ServerInfo> {
  late Server _server;

  _ServerInfoState({required Server server}) {
    _server = server;
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(_server.name),
    );
  }
}

Following the first two examples we can pass parameters through the widget hierarchy, but only down the hierarchy, if we need to send the parameters up the hierarchy we must send the parameter through "Navigator.pop(context)" and catch information higher up in the hierarchy, but a state management approach is much better practice:

https://docs.flutter.dev/data-and-backend/state-mgmt/options

Comments

-1

To pass data to stateful widget, first of all, create two pages. Now from the first page open the second page and pass the data.

class PageTwo extends StatefulWidget {
  final String title;
  final String name;

  PageTwo ({ this.title, this.name });

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

class PageTwoStateState extends State<PageTwo> {
  @override
  Widget build(BuildContext context) {
      return Text(
         widget.title,
         style: TextStyle(
               fontSize: 18, fontWeight: FontWeight.w700),
               ),
  }
}

class PageOne extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialButton(
          text: "Open PageTwo",
          onPressed: () {
                var destination = ServicePage(
                   title: '<Page Title>',
                   provider: '<Page Name>',
                );
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) => destination));
                        },);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.