1

As I learned that state of StatefulWidget widget in flutter defined as private and both of snippet of VS Code , and android studio do this like below on _RectAnsState

class RectAns extends StatefulWidget {
  final String title;
  const RectAns(this.title, {Key key}) : super(key: key);

  @override
  _RectAnsState createState() => _RectAnsState();
}

class _RectAnsState extends State<RectAns> {
  Color _color = Colors.transparent;

 
  @override
  Widget build(BuildContext context) {
    return Container()}
}

although i pass GlobalKey to widget so i can use this key to get currentState object , but i need to define that currentState object type from other files , but it's type is private class then its must be public here, what wrong of my implementation

GlobalKey gk = new GlobalKey();
RectAns rectAns = new RectAns(count.toString(), key: gk);

and on other file i want to get this state to call function inside and setState

RectAnsState rt = gk.currentState

above RectAnsState is private , so is the correct way to make it public?????

3 Answers3

3

Instead of

_RectAnsState createState() => _RectAnsState();

write this:

State<RectAns> createState() => _RectAnsState();
M Karimi
  • 1,991
  • 1
  • 17
  • 34
1

You can remove underline _ to make it public
You can change from

class _RectAnsState extends State<RectAns> {

to

class RectAnsState extends State<RectAns> {
chunhunghan
  • 51,087
  • 5
  • 102
  • 120
1

The State class should be private indicating it should not be created anywhere outside createState override, because you should not create/manage State object instance at all (see here and here).

In your case you don't create/manage State object but only need to access already created object through key. Same mechanism exists in Flutter official widgets like Form. There you have validation function bool validate() stored in Form's State class, so to access it you need an instance of FormState. You can obtain it from global key like this:

GlobalKey gk = GlobalKey(); // Notice that it's untyped!
GlobalKey typedGK = GlobalKey<FormState>(); // FormState has to be public

void myCallback() {
  // untyped, so code fails as it doesn't know validate() exists :(
  gk.currentState.validate();
  // typed, so everything is fine
  typedGK.currentState.validate();
}

Widget build(...) {
  return Form(
    key: gk,
    ...
  );
}

So Flutter official widgets use this mechanism if they need typed access to State object and obtain this object through key. Hence it should be perfectly fine to repeat this pattern in our own widgets.

Outside of that I can't think of a "good" reason to make your State class public and it's better to keep it private.

Georgii
  • 442
  • 4
  • 11