Flutter: The instance member 'data' can't be accessed in an initializer

Viewed 2700
 class _ShowformState extends State<Showform> {
  List data;

  var duplicateItems = List<String>.from(data); //<---- The instance member 'data' can't be accessed in 
  //an  initializer.

  var items = List<String>();

@override
Widget build(BuildContext context) {
return Scaffold(
    appBar: AppBar(
      elevation: 0.0,
      title:
          Text('Maintenance Information', style: TextStyle(fontSize: 20)),
    ),

I would like to convert List< dynamic> to List< string> but I can't access data.

2 Answers

You should initialize the fields in the class constructor:

  final List data;

  final List<String> duplicateItems;

  _ShowformState({this.data}) : duplicateItems = List<String>.from(data);

You have several possibilities:

1- The first possibility is to access the variable "data" in the build method.

Code :

class Showform extends StatefulWidget {
  @override
  _ShowformState createState() => _ShowformState();
}

class _ShowformState extends State<Showform> {
  List data;
  @override
  Widget build(BuildContext context) {
    var duplicateItems = List<String>.from(data);  //here
    return Scaffold(
     // Your code
    );
  }
}

2- The second possibility is to use the access by instance and in this case you keep the same code.

class _ShowformState extends State<Showform> {
  List data;
  var duplicateItems = List<String>.from(_ShowformState().data);
     //build method and your code 
}

If the variable data was a static variable (static var) in this case, it will not be access by instance but rather static access.

Code for static access :

static List data;
var duplicateItems = List<String>.from(_ShowformState.data);
Related