On Flutter we can create method inside inside the build method, but why we cant create getter(get).
Minimal reproducible snippet
class A extends StatefulWidget {
const A({super.key});
@override
State<A> createState() => _AState();
}
class _AState extends State<A> {
int get _foo => 0; // Ok
@override
Widget build(BuildContext context) {
int get _bar => 1; /// invalid
return Container();
}
}
class B extends StatelessWidget {
const B({super.key});
@override
Widget build(BuildContext context) {
int get _bar => 1; /// invalid
return Container();
}
}
I am using flutter_lints: ^3.0.0. Is it possible to create getter inside build method?
Getters can't be declared locally inside a method.
This's because of the intended usage of these getters, it's intended to be encapsulated within the instances of the class in which they are declared.
So, Getters are special methods that provide explicit read access to an object's properties. and must be declared on class level not locally inside a method.
actually, this answer should be long to explore some concepts like encapsulation. However, we can ask some questions that explain why not locally.
suppose it can.
object can't even see that static method.
So, it must be declared at class level to perform as supposed.