我对 Flutter 的使用还很陌生,但我非常喜欢这门语言及其强大的功能。现在我面临以下问题:
我想构建一个继承树,从 StatefulWidget 开始,然后是 2 个抽象类。我当然会以一个非抽象对象结束。我知道这意味着扩展小部件的编码很糟糕,但我只想了解我的问题。这是代码:
import 'package:flutter/material.dart';
abstract class Widget1 extends StatefulWidget {
const Widget1({super.key});
}
abstract class Widget1State<T extends Widget1> extends State<T> {
@override
Widget build(BuildContext context) {
return Container(); //Some abstraction here
}
}
abstract class Widget2 extends Widget1 {
const Widget2({super.key});
}
abstract class Widget2State extends Widget1State {
@override
Widget build(BuildContext context) {
return Container(); //Some abstraction here
}
}
class Widget3 extends Widget2 {
final int i;
const Widget3(this.i, {super.key});
@override
State createState() => Widget3State();
}
class Widget3State extends Widget2State {
void a() {
widget.i = 0;
}
}
widget.i = 0 末尾的行显示错误;显示的提示包含以下文本:
The setter 'i' isn't defined for the type 'Widget1'.
Try importing the library that defines 'i', correcting the name to the name of an existing setter, or defining a setter or field named 'i'.
为什么要在 Widget1 中声明变量 i ?它在 Widget3 中声明,并在相关 Widget3State 中通过 widget-prefix 引用...
根据我对继承和flutter文档的“知识”,这不应该是一个错误......任何人都可以解释问题出在哪里以及我可以做得更好,以便在widget3中声明变量并在Widget3State中引用变量吗?
提前非常感谢!
您遇到的错误是因为 widget.i 正在尝试访问 Widget1 类型的 widget 字段的 i 属性。由于 Widget1 没有属性 i.
解决方法如下:
import 'package:flutter/material.dart';
abstract class Widget1 extends StatefulWidget {
const Widget1({Key? key}) : super(key: key);
}
abstract class Widget1State<T extends Widget1> extends State<T> {
@override
Widget build(BuildContext context) {
return Container(); //Some abstraction here
}
}
abstract class Widget2 extends Widget1 {
const Widget2({Key? key}) : super(key: key);
}
abstract class Widget2State extends Widget1State {
@override
Widget build(BuildContext context) {
return Container(); //Some abstraction here
}
}
class Widget3 extends Widget2 {
final int i;
const Widget3(this.i, {Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() => Widget3State();
}
class Widget3State extends Widget2State {
void a() {
(widget as Widget3).i = 0; // Cast widget to Widget3 to access i property
}
}
在 Widget3State 中,您需要将 widget 转换为 Widget3 才能访问 i 属性,因为 Widget1State 不知道 Widget3 的属性。