【发布时间】:2020-09-03 11:04:54
【问题描述】:
我在使用 Flutter 时遇到了一些奇怪的问题。我对 Flutter 知之甚少。我正在学习它。
class ViewOtherProfile extends StatefulWidget {
final String userName;
final int points;
const ViewOtherProfile({
@required this.userName,
@required this.points,
});
您可以看到我将 userName 和 Points 数据作为参数。 我想在页面中打印这个参数。像这样
class _ViewOtherProfileState extends State<ViewOtherProfile> {
..........
void initState(){
print(points);
deviceInfo();
super.initState();
print(userName);
]);
}
............
现在的问题是我遇到了错误。
Undefined name 'userName'.
Try correcting the name to one that is defined, or defining the name.
我收到此错误的任何原因以及如何解决它。
感谢@jamesdlin
我试着这样写
print(ViewOtherProfile.userName);
但现在我又遇到了另一个错误。
Instance member 'userName' can't be accessed using static access.
【问题讨论】:
-
userName是ViewOtherProfile的成员,而不是_ViewOtherProfileState的成员。您可以使用widget.userName从_ViewOtherProfileState访问它。 -
@jamesdlin 感谢您的建议,任何示例都会非常有帮助。我不了解widget.userName。
-
jamesdlin 的意思是 userName 是小部件的一部分,即 ViewOtherProfile,而不是状态对象 (_ViewOtherProfileState)。为了在状态对象中使用 userName,您可以通过执行 widget.userName 从小部件中获取它
-
@Unbreachable 感谢您的澄清。我试过 print(ViewOtherProfile.userName);但现在我可以在打印和用户名上看到错误。无法使用静态访问访问实例成员“用户名”。
-
不,ViewOtherProfile.userName 不正确。 ViewOtherProfile is 具有您声明的属性的有状态小部件本身。已经澄清你像这样使用它 widget.userName