1

I am retrieving data from Firestore in the form of two functions (_onpressed() and _drname()) and called both of them in FutureBuilder.

Function 1 is

  Future _onPressed() async {
if (widget.brew.id == currentid.userid()) {
  return await db
      .collection('Messages')
      .doc(widget.brew.id)
      .get()
      .then((DocumentSnapshot documentSnapshot) {
    if (documentSnapshot.exists) {
      print('${documentSnapshot.data()['Message']}');
      String msg = json.encode(documentSnapshot.data()['Message']);
      

      return msg;
    } else {
      print('Document does not exist on the database');
    }
    // var a= documentSnapshot.data()['Message'];
  });
} else {
  return 'No Prescription from doctor yet';
}}

Function 2 is

Future _drname() async {
if (widget.brew.id == currentid.userid()) {
  return await db
      .collection('Drname')
      .doc(widget.brew.id)
      .get()
      .then((DocumentSnapshot documentSnapshot) {
    if (documentSnapshot.exists) {
      print('${documentSnapshot.data()['name']}');
      String msg = json.encode(documentSnapshot.data()['name']);
      return msg;
    } else {
      print('Document does not exist on the database');
    }
    // var a= documentSnapshot.data()['Message'];
  });
} else {
  return 'No';
}}

Calling these functions in FutureBuilder like this

Widget _messagePannel() {
return FutureBuilder(
    future: Future.wait([_onPressed(),_drname()]),
    builder: (BuildContext context, AsyncSnapshot<List> snapshot) {
      return Scaffold(
        appBar: AppBar(
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 17.0),
              child: TextButton.icon(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => Call()),
                  );
                },
                icon: Icon(
                  Icons.video_call,
                  color: Colors.white,
                  size: 30.0,
                ),
                label: Text(''),
              ),
            )
          ],
          title: Text(
            'Prescrption',
            style: TextStyle(fontFamily: 'RussoOne', fontSize: 22.0),
          ),
          backgroundColor: Colors.green[900],
          elevation: 0.0,
          centerTitle: true,
        ),
        body: Container(
          decoration: image,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              children: [
                Expanded(
                  child: SingleChildScrollView(
                    child: Card(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(5),
                      ),
                      color: Colors.black,
                      child: Center(
                          child: Padding(
                        padding: EdgeInsets.fromLTRB(0.0, 4.0, 4.0, 4.0),
                        child: Wrap(
                          children: [
                            Center(
                              child: Text(
                                '${snapshot.data[0]} ',
                                textAlign: TextAlign.left,
                                style: TextStyle(
                                    fontFamily: 'RussoOne',
                                    color: Colors.white,
                                    letterSpacing: 0.8,
                                    fontSize: 18.0,
                                    backgroundColor: Colors.black),
                              ),
                            ),
                            Center(
                              child: Text(
                                '${snapshot.data[1]} ',
                                textAlign: TextAlign.left,
                                style: TextStyle(
                                    fontFamily: 'RussoOne',
                                    color: Colors.white,
                                    letterSpacing: 0.8,
                                    fontSize: 18.0,
                                    backgroundColor: Colors.black),
                              ),
                            ),
                          ],
                        ),
                      )),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    });}

Getting This error from the Debug Console

The following NoSuchMethodError was thrown building FutureBuilder<List>(dirty, state: _FutureBuilderState<List>#44f46): The method '[]' was called on null. Receiver: null Tried calling:

Error image

1 Answers1

1

When using snapshot, the initial value for the data property is null (since Future has no result until you receive the response), so using it straight away as you do it in the code (e.g. snapshot.data[1]) should be avoided.

To cope with that, first of all you should check if the data is not null. For that, snapshot has a dedicated method snapshot.hasData, for instance:

return FutureBuilder(
    future: Future.wait([_onPressed(),_drname()]),
    builder: (BuildContext context, AsyncSnapshot<List> snapshot) {
        if (!snapshot.hasData) {
            return CircularProgressIndicator(); // E.g. Show loader if there is no data yet
        }

        return Scaffold(...); // Return the widget you have now
    },
);
mkobuolys
  • 4,499
  • 1
  • 11
  • 27