gpt4 book ai didi

flutter/飞镖 : StatefulWidget - access class variable inside Widget

转载 作者:行者123 更新时间:2023-12-02 16:17:45 28 4
gpt4 key购买 nike

我为 StatefulWidget 声明了一个类变量 - 在下面的代码中它是 someString。是否可以在 build(...) 方法中使用此变量而不将其声明为静态变量?

class MyClass extends StatefulWidget {
String someString;
MyClass() {
this.someString = "foo";
}
@override
_MyClassState createState() => _MyClassState();
}

class _MyClassState extends State<MyClass> {
_MyClassState();

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("someString - how to access it here?!"),
// title: Text(someString), is not possible, obviously
),
);
}
}

在此先感谢您的帮助!

最佳答案

注意:MyClass 应该是不可变的。

1。如果 someString 永远不会改变

将其保存在 MyClass 中,但将其定义为 final。

class MyClass extends StatefulWidget {
final String someString;

const MyClass({Key key, this.someString = 'foo'}) : super(key: key);

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

然后,在 State 内部,您可以将其用作 widget.someString:

class _MyClassState extends State<MyClass> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('${widget.someString} is accessed here?!')),
);
}
}

2。如果 someString 会改变

应该在状态中定义。

class MyClass extends StatefulWidget {
final String initialValue;

const MyClass({Key key, this.initialValue = 'foo'}) : super(key: key);

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

class _MyClassState extends State<MyClass> {
String someString;

@override
void initState() {
someString = widget.initialValue;
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('$someString is accessed here?!')),
body: Center(
child: OutlinedButton(
onPressed: () => setState(() => someString = 'NEW Value'),
child: Text('Update value'),
),
),
);
}
}

enter image description here

关于 flutter/飞镖 : StatefulWidget - access class variable inside Widget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66217240/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com