Victor Ortiz
Victor Ortiz

Reputation: 911

How to resolve "Only static members can be accessed in initializers" in flutter?

I'm developing a flutter app, where I need to scan some barcodes, so, for that, I use a plugin called barcode_scan (https://pub.dartlang.org/packages/barcode_scan). So, the problem comes when I try to call a function from a RaisedButton which is stored on a List of Steps, because I need show that button inside Stepper widget, when I call the function for init the barcode scanner on the onPressed, Android studio show this message 'only static members can be accessed in initializers'.

The function for init barcode scanner:

Future scan() async {
try {
  String barcode = await BarcodeScanner.scan();
  setState(() => this.barcode = barcode);
} on PlatformException catch (e) {
  if (e.code == BarcodeScanner.CameraAccessDenied) {
    setState(() {
      this.barcode = 'The user did not grant the camera permission!';
    });
  } else {
    setState(() => this.barcode = 'Unknown error: $e');
  }
} on FormatException{
  setState(() => this.barcode = 'null (User returned using the "back"-button before scanning anything. Result)');
} catch (e) {
  setState(() => this.barcode = 'Unknown error: $e');
}}

And the code for the Step List

List<Step> mySteps = [
new Step(title: new Text("Scan first"),
    content: new Column(
      children: <Widget>[
        new Text("Code"),
        new Container(
          padding: EdgeInsets.only(top: 20),
          child: new Text("A08B",style: TextStyle(
              fontSize: 30,
              color: Colors.red
          ),
        )
        ,),
        new Container(
          child: new RaisedButton(onPressed: scan ,
          child: new Text("Scan"),),
        )
      ],
    ))];

Full dart class:

void main() => runApp(MaterialApp(
        home: Ubicacion(),
    ));

class Ubicacion extends StatefulWidget {
@override
_UbicacionState createState() => _UbicacionState();}
class _UbicacionState extends State<Ubicacion> {

String barcode = "";
Future scan() async {
    try {
        String barcode = await BarcodeScanner.scan();
        setState(() => this.barcode = barcode);
    } on PlatformException catch (e) {
        if (e.code == BarcodeScanner.CameraAccessDenied) {
            setState(() {
                this.barcode = 'The user did not grant the camera permission!';
            });
        } else {
            setState(() => this.barcode = 'Unknown error: $e');
        }
    } on FormatException{
        setState(() => this.barcode = 'null (User returned using the "back"-button before scanning anything. Result)');
    } catch (e) {
        setState(() => this.barcode = 'Unknown error: $e');
    }
}


@override
Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text('hello'),
        ),
        body: Container(
            padding: EdgeInsets.all(32.0),
            child: Center(
                child: Column(
                    children: <Widget>[

                        new Container(
                            child: new Stepper(steps: mySteps,
                            currentStep: this.pasoActual,
                            onStepContinue: (){
                                setState(() {
                                    if(pasoActual <mySteps.length -1){
                                        pasoActual++;
                                    }else{
                                        pasoActual = 0;
                                    }
                                });
                            },
                            onStepCancel: (){
                                setState(() {
                                    if(pasoActual >0){
                                        pasoActual--;
                                    }else{
                                        pasoActual = 0;
                                    }
                                });
                            },),
                        )


                    ],
                ),
            ),
        ),
    );
}

int pasoActual = 0;
List<Step> mySteps = [
    new Step(title: new Text("Escanear palet"),
            content: new Column(
                children: <Widget>[
                    new Text("Codigo"),
                    new Text("ID",),
                    new Text("PLU"),
                    new Container(
                        padding: EdgeInsets.only(top: 20),
                        child: new Text("A08B",style: TextStyle(
                                fontSize: 30,
                                color: Colors.red
                        ),
                        )
                        ,),
                    new Container(
                        child: new RaisedButton(onPressed: null ,
                            child: new Text("Escanear"),),
                    )
                ],
            ))
];

}

Upvotes: 3

Views: 6769

Answers (1)

bytesizedwizard
bytesizedwizard

Reputation: 6033

The above error occurs when you try to initialize a non-static variable directly when declaring it inside a class. In your case I assume it's the mySteps list which you are initializing directly.

Try initializing it inside your initState() method if you are using a Stateful Widgetor inside a class constructor and the error will go away.

You can also check this answer for a detailed explanation regarding the same issue.

Upvotes: 12

Related Questions