"类中的字段时出错-6ren"> "类中的字段时出错-此类实现的目的 为 admin 显示不同的 View 和 user登录后 Scaffold body . 错误 使用 Widget 时显示以下错误作为 State 内的字段类。 '_NormalMen-6ren">
gpt4 book ai didi

flutter - 在 flutter 中将 "Widget"添加为 "State"类中的字段时出错

转载 作者:IT王子 更新时间:2023-10-29 07:15:08 25 4
gpt4 key购买 nike

此类实现的目的

admin 显示不同的 View 和 user登录后 Scaffold body .

错误

使用 Widget 时显示以下错误作为 State<NormalMenuState> 内的字段类。

'_NormalMenuState.widget' ('() → Widget') isn't a valid override of 'State.widget' ('() → NormalMenuState')

代码

class NormalMenu extends StatelessWidget {
final String userType;

NormalMenu({this.userType});

@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(this.userType),
);
}
}

class NormalMenuState extends StatefulWidget {
final String userType;

NormalMenuState(this.userType);

@override
State<StatefulWidget> createState() => _NormalMenuState(userType: this.userType);
}

class _NormalMenuState extends State<NormalMenuState> {
String appTitle = 'Welcome';
final String userType;
Widget widget; //<= `This line shows error`

_NormalMenuState({this.userType});

@override
void initState() {
if (this.userType == UserType.admin) {
this.appTitle = "User Information";
widget = UserInformation();
} else {
this.appTitle = "Pay Fair";
widget = BookTicket();
}
super.initState();
}

最佳答案

如果你查看源代码:

abstract class State<T extends StatefulWidget> extends Diagnosticable {
T get widget => _widget;

有一个widget getter 用于访问相关的StatefulWidget 类。问题不在于将 Widget 创建为实例字段,而是您的错误指出的名称:

'_NormalMenuState.widget' ('() → Widget') isn't a valid override of 'State.widget' ('() → NormalMenuState')

因此更改变量的名称:

Widget widget; => Widget myWidget;

关于flutter - 在 flutter 中将 "Widget"添加为 "State<NormalMenuState>"类中的字段时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57620424/

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