Riyazat Durrani
Riyazat Durrani

Reputation: 668

The method '[]' was called on null on restart

i am getting this error as i restart the app

    The method '[]' was called on null.
Receiver: null
Tried calling: [](0)

my code is:

    class UserScore extends StatefulWidget {
  String uid;
  UserScore(String uid){
    this.uid = uid;
  }
  @override
  _UserScoreState createState() => _UserScoreState();
}

class _UserScoreState extends State<UserScore> {
@override
var lengthofscore;
var eventt;

Future getRequest() async{
  CollectionReference collectionReference =  FirebaseFirestore.instance.collection('score');

  await collectionReference.doc(widget.uid).collection("indivisualscore").snapshots().listen((event) {

    lengthofscore= event.docs.length;
      eventt=event.docs;
      print(eventt[0].data()); // prints {score: 10}
      var b= eventt[0].data()['score'].toString();
      print(b); // prints 10
    });

}

  void initState() {

  getRequest();
    super.initState();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(

      body: Center(
        child:ListView.builder
          (
            itemCount: lengthofscore,
            itemBuilder: (BuildContext context, int index) {
              return Text(eventt[index].data()['score'].toString());
            }
        )
      ),
    );
  }
}

so while i am printing the data, although for 0th element, it gives me correct output in console, but with same code in listviewbuilder,it gives me the error above. also when i hot reload,the listviewbuilder works fine,but again if i hot restart,or install the app again, the same error persists.

Upvotes: 2

Views: 108

Answers (1)

hasan karaman
hasan karaman

Reputation: 1430

You can't write async method directly in initstate because of it. I'm also sorry I might have mistyped the parentheses. It would be better if you add a null check in builld.

      void initState() {

    getRequest();
    super.initState();
    }

  future getRequest() async{
   await FirebaseFirestore.instance.collection('score').then((result){
    result.doc(widget.uid).collection("indivisualscore").snapshots().listen((event) {
   
    lengthofscore= event.docs.length;
       setState(() 
     { eventt=event.docs; });

    
    print(eventt[0].data()); // prints {score: 10}
    var b= eventt[0].data()['score'].toString();
    print(b); // prints 10
    });
        });
    }

------ and------

 @override
  Widget build(BuildContext context) {
     return Scaffold(

      body:lengthofscore==null?container(): Center(
     child:ListView.builder
       (
        itemCount: lengthofscore,
        itemBuilder: (BuildContext context, int index) {
          return Text(eventt[index].data()['score'].toString());
        }
       )
     ),
    );
   }
  } 

Upvotes: 4

Related Questions