How to use a global key outside the file widget had been defined
1,033
Remove the underscore from in front of your _MyWidgetState to make it public. Change
_MyWidgetState
to
MyWidgetState
Author by
woshitom
Updated on December 12, 2022Comments
-
woshitom over 1 year
In file1 I'm defining the following widget:
class MyWidget extends StatefulWidget { const MyWidget({ Key key, }) : super(key: key); @override _MyWidget createState() => _MyWidgetState(); }
In file2 I want to call this widget and give a global key for the key parameter. To do so I'm importing file1:
import 'package:mypackage/supplemental/file1.dart';
Then in this file (file2) I want to define a MyWidget global key:
GlobalKey<_MyWidgetState> globalKey;
But I'm getting this error:
The name '_MyWidgetState' isn't a type so it can't be used as a type argument. Try correcting the name to an existing type, or defining a type named '_MyWidgetState'
How come I cannot access it even though I imported the file?
-
danypata almost 5 yearsIf you have a
_
before a class or a variable declaration, it means that class or variable is private. In your case_MyWidgetState
is private and can't be accessed from a different file. You can remove the_
from the class declaration and then it should work.
-