I'm quite new in using Flutter but I like the language and its power very much. Now I'm facing the following problem :
I want to build an inheritance tree , beginning with a StatefulWidget and following 2 abstract classes. I will of course end with a non-abstract object. I know that it's meant to be bad coding extending widgets, but I only want to understand my problem. This is the code :
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;
}
}
An error is shown in the line at the end with widget.i = 0; The hint which is shown contains the following text:
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'.
Why should variable i be declared in Widget1 ? It's declared in Widget3 and referenced with widget-prefix in related Widget3State ...
According to my "knowledge" of inheritance and flutter documentation that should not be an error ... Can anybody please explain where the problem is and what I could do better to have the variable declared in widget3 and referenced in Widget3State ?
Thanks a lot in advance !
The error you're encountering is because widget.i is trying to access the i property of the widget field which is of type Widget1. Since Widget1 does not have a property i.
Here's how you can fix it:
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
}
}
In the Widget3State, you need to cast widget to Widget3 to access the i property since Widget1State doesn't know about the properties of Widget3.