Home > Back-end >  The instance member 'value' can't be accessed in an initializer. Try replacing the re
The instance member 'value' can't be accessed in an initializer. Try replacing the re

Time:12-14

I am hoping to use value passed on from another widget in one of the references for a collection within a document. However, this error pops up:

The instance member 'value' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression

How should I go about this?

class FriendProfileScreen extends StatefulWidget {
  String value;
  FriendProfileScreen({Key? key, required this.value}) : super(key: key);

  @override
  _FriendProfileScreenState createState() => _FriendProfileScreenState(value);
}

class _FriendProfileScreenState extends State<FriendProfileScreen> {
  String value;
  _FriendProfileScreenState(this.value);

  var uid = value;
  final CollectionReference _todoref = FirebaseFirestore.instance
      .collection("users")
      .doc(value)
      .collection("todos");
  @override

CodePudding user response:

I'd suggest to mark it late, so like

  late final CollectionReference _todoref = FirebaseFirestore.instance
      .collection("users")
      .doc(value)
      .collection("todos");

CodePudding user response:

Put your initializing code into a future type function and call the function in init method. It will work.

 var uid;    
 Future loadData()async{
 uid = value;
 final CollectionReference _todoref = FirebaseFirestore.instance
  .collection("users")
  .doc(value)
  .collection("todos");
}
@override
  void initState() {
    loadData();
    super.initState();
  }
  • Related