在哪里存储与有状态小部件关联的值?

6 flutter

class MyWidget extends StatefulWidget {
  // Here?

  @override
  State<MyWidget> createState() => MyWidgetState();
}

class MyWidgetState extends State<MyWidget> {
  // Or here?

  // ...
}
Run Code Online (Sandbox Code Playgroud)

我想了解在哪里存储与有状态小部件关联的值。在小部件上还是在状态上?

Joã*_*res 3

请查看代码中的注释以了解每个用例:

class AnotherWidget extends StatefulWidget {
  final String fromParentVariable;

  AnotherWidget({
    this.fromParentVariable
  });

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

class _AnotherWidgetState extends State<AnotherWidget> {
  String localVariable;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        // You can access the variable coming from the parent by using the "widget." prefix.
        Text(widget.fromParentVariable),
        // You can access a local variable by simply calling normaly.
        Text(localVariable),
      ],
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

调用 Widget 时,您将执行以下操作:

AnotherWidget(fromParentVariable: 'my string',)
Run Code Online (Sandbox Code Playgroud)