Flutter类继承问题:AccountEditPageState无法访问widget.uuid
Flutter嵌套类继承问题排查:访问widget.uuid报错的解决方法
错误原因
你遇到的The getter 'uuid' isn't defined for the type 'AccountAddPage'错误,核心问题出在AccountAddPageState的泛型约束上:
原本的AccountAddPageState继承AbstractPageState时,硬把类型参数写死成了AccountAddPage,而不是用自己定义的泛型参数T。这就导致不管子类指定什么泛型类型,widget的类型都会被强制限定为AccountAddPage,而AccountAddPage并没有uuid属性,所以报错。
修复步骤
- 修改
AccountAddPageState的继承声明,将AbstractPageState<AccountAddPage>改为AbstractPageState<T>,让泛型参数传递生效:
class AccountAddPageState<T extends AccountAddPage> extends AbstractPageState<T> { String? get title => widget.title; // 依然正常工作 }
- (可选但更严谨)调整
AccountAddPage的createState方法,明确返回泛型类型:
class AccountAddPage extends AbstractPage { String? title; AccountAddPage({ this.title, }) : super(); @override AccountAddPageState<AccountAddPage> createState() => AccountAddPageState<AccountAddPage>(); }
修复后的完整代码
import 'package:flutter/material.dart'; class AccountEditPage extends AccountAddPage { String uuid; AccountEditPage({ required this.uuid, }) : super(); @override AccountEditPageState createState() => AccountEditPageState(); } class AccountEditPageState extends AccountAddPageState<AccountEditPage> { String get uuid => widget.uuid; // 现在可以正常访问uuid了 } class AccountAddPage extends AbstractPage { String? title; AccountAddPage({ this.title, }) : super(); @override AccountAddPageState<AccountAddPage> createState() => AccountAddPageState<AccountAddPage>(); } class AccountAddPageState<T extends AccountAddPage> extends AbstractPageState<T> { String? get title => widget.title; // 正常工作 } abstract class AbstractPage<T> extends StatefulWidget { int selectedMenu = 0; AbstractPage() : super(key: UniqueKey()); } abstract class AbstractPageState<T extends AbstractPage> extends State<T> { @override Widget build(BuildContext context) { return Text('test'); } }
原理说明
修改后,AccountAddPageState的泛型参数T会向下传递给父类AbstractPageState,widget的类型就会被正确推断为当前页面的实际类型(比如AccountEditPage),这样就能正常访问子类特有的属性uuid了。
内容的提问来源于stack exchange,提问作者FieryCat
相关产品推荐
相关产品推荐

