Search code examples
classflutterdartinitializationstatic-variables

Unable to initialize static member in Dart


I have read similar questions

  1. Error: Only static members can be accessed in initializers what does this mean?
  2. Dart - Only static members can accessed in initializers

But I am still unable to solve the problem.

I am sending Ip object which has a Ip string from one screen to another.

Here is Second screen's widget and state class in short.

class DrawingPage extends StatefulWidget {
  Ip ipObj;
//  String ipObj;
  DrawingPage({Key key, @required this.ipObj});
  _DrawingPageState createState() => _DrawingPageState();
}
class _DrawingPageState extends State<DrawingPage> {

  final String ip = widget.ipObj.ip;     //Error at "widget": Only Static members can be accessed in initializers


}

I have tried

1.Initializer's List.

2.Converting final to static member and then assigning ip value in initState does work.

But the value is set when initState is invoked, but I want to set value before initState.

How should I do it?


Solution

  • There are a number of options here... I'm not sure which one would be best for your case, but I usually use the second one, as I don't like to reference the 'widget' object in the state all the time:

    Option 1: convert 'ip' to a field

    class _DrawingPageState extends State<DrawingPage> {
      String get ip => widget.ipObj.ip;
    }
    

    Option 2: pass the ipObj in the constructor of the state:

    class DrawingPage extends StatefulWidget {
      Ip ipObj;
    
      DrawingPage({Key key, @required this.ipObj});
    
     _DrawingPageState createState() => _DrawingPageState(ipObj);
    }
    
    class _DrawingPageState extends State<DrawingPage> {
    
      String ip;
    
      DrawingPageState(Ip ipObj){
        ip = ipObj.ip;
      }
    }