How to Resolve Only Static Members can be Accessed in Initializers In Flutter

How to Resolve Only Static Members can be Accessed in Initializers In Flutter?

Earlier we have been through various articles based on flutter like how to Run App On Multiple Connected Devices Simultaneously in the flutter. So in this article, we will go through how to resolve Only Static Members can be Accessed in Initializers in Flutter.

In this blog post, we’ll provide you with a step-by-step guide on resolving the “Only Static Members can be Accessed in Initializers” error in Flutter. If you’ve encountered this error while initializing variables or objects in your Flutter code, this comprehensive guide is here to help you understand the issue and provide solutions.

Resolve Only Static Members can be Accessed in Initializers In Flutter

is an initializer and there is no way to access this at this point. Initializers are executed before the constructor, but this is only allowed to be accessed after the call to the super constructor implicit in your example was completed.

Therefore only in the constructor body access to this is allowed.

class AppHomeState extends State<AppHome> with SingleTickerProviderStateMixin {

    TabController _tabController;
    final filterController = new TextEditingController(text: "Search");
    TextFormField email = ...

This is why you get the error message:

controller: filterController,

accesses this.filterController

To work around your issue assuming email needs to be final you can use a factory constructor and a constructor initializer list:

class AppHomeState extends State<AppHome> with SingleTickerProviderStateMixin {
  factory SingleTickerProviderStateMixin() => 
      new SingleTickerProviderStateMixin._(new TextEditingController(text: "Search"));

  SingleTickerProviderStateMixin._(TextEditingController textEditingController) : 
      this.filterController = textEditingController,   
      this.email = new TextFormField(
        keyboardType: TextInputType.emailAddress,
        controller: textEditingController);

  TabController _tabController;
  final filterController;
  final TextFormField email;

or when the email field does not need to be final email can be initialized in the constructor initializer list:

class AppHomeState extends State<AppHome> with SingleTickerProviderStateMixin {

  SingleTickerProviderStateMixin() {
    email = new TextFormField(
        keyboardType: TextInputType.emailAddress,
        controller: filterController,
    );
  }

  TabController _tabController;
  final filterController = new TextEditingController(text: "Search");
  TextFormField email;

but in Flutter widgets, initState() is usually used for that

class AppHomeState extends State<AppHome> with SingleTickerProviderStateMixin {

  @override
  void initState() {
    super.initState();
    email = new TextFormField(
        keyboardType: TextInputType.emailAddress,
        controller: filterController,
    );
  }

  TabController _tabController;
  final filterController = new TextEditingController(text: "Search");
  TextFormField email;

You can convert this variable to a function and you can take context in these function parameters.

The code snippet will look like the below:

Widget myDialog (BuildContext context) {
  return new Scaffold(
    backgroundColor: Colors.white,
    body: new Center(
      child: new Column(
        children: <Widget>[
          new Text("Invalid Username/Password"),
          new Text("Please verify your login credentials"),
          new RaisedButton(
            child: new Text("Ok"),
            onPressed:() {
              Navigator.pop(context);//Error : Only static members can be accessed in initializers
            }
          ),
        ],
      ),
    )
  );
}

// Using if you are doing in a class
this.myDialog(context);

// Using if you are using a global function
myDialog(context);

But, I think you want to show an error message. So, you can do it with a dialog, not a page.

It’s more efficient because you can specify your dialog box with buttons or messages and you can use this error dialog everywhere.

Let’s look at my global helper function for showing error messages.

void showError(BuildContext context, String error) {
  showSnackBar(
    context,
    new Text(
      'Error',
      style: new TextStyle(color: Theme.of(context).errorColor),
    ),
    content: new SingleChildScrollView(
      child: new Text(error)
    ),
    actions: <Widget>[
      new FlatButton(
        child: new Text(
          'Ok',
          style: new TextStyle(
            color: Colors.white
          ),
        ),
        onPressed: () {
          Navigator.of(context).pop();
        },
        color: Theme.of(context).errorColor,
      ),
    ]
  );
}

// Using in everywhere
showError(context, 'Sample Error');

You can keep that as a method:

Widget getEmailController(){
return new TextFormField(
        keyboardType: TextInputType.emailAddress,
        controller: filterController,
        );
}

and use it in UI:

body: Container(
child: getEmailController();
)
  • You can do it this way: first declared and after initialized inside your didChangeDependencies() method, like this declared your variable
    List<Tab> tabsList = [];
  • initialized tabs list
    tabsList = [
        Tab(text: getTranslated(context, "tab_1")),
        Tab(text: getTranslated(context, "tab_2")),
        Tab(text: getTranslated(context, "tab_3"))
     ];
  • Full codes example will look like a below:
    class _MyClassState extends State<MyClass>
        with TickerProviderStateMixin<MyClass> {
    
      TabController tabController;
      List<Tab> tabsList = [];
    
      @override
      void didChangeDependencies() {
        tabsList = [
          Tab(text: getTranslated(context, "tab_1")),
          Tab(text: getTranslated(context, "tab_2")),
          Tab(text: getTranslated(context, "tab_3"))
        ];
        tabController =
            TabController(length: tabsList.length, vsync: this, initialIndex: 0);
    
        super.didChangeDependencies();
      }
    }

Conclusion:

Keep Learning, Keep fluttering!!!

So in this article, we have been through how to resolve only static members can be accessed in initializers in flutter.

Do not forget to drop your valuable suggestions/feedback. We would love to assist you.

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

Your email address will not be published. Required fields are marked *

Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields