在api调用中使用提供程序

时间:2020-04-23 20:36:50

标签: flutter

我有一个可以进行api调用的方法。在该方法中,我想保存从调用到Firestore的数据。我的Firestore数据库正在使用提供程序进行注入。

    Future<String> getData(String query) async {
    print('getdata called');
    List<Suburb> suburbs = await model.getSuburbs('au', query);

    if (suburbs.length == 1) {
      final suburb= suburbs[0];
      final database = Provider.of<Database>(context);   // My firestore database. When I remove these lines, I get the expected return. 
      await database.setSuburb(suburb);
     return suburb.name;

    } else...{return}

Removing the firestore write, gives me the expected return. But when I try to save the data, I don't get anything returned. The write never happens either.  So I presume the problem is there or maybe I'm doing something incorrect in the method. I don't get any error logs either...

here is the firestore method:


    setSuburb(Suburb suburb)async{
        final path = '/voters/$uid/';
        final documentReference = Firestore.instance.document(path);
         await documentReference.setData({"location.suburb":suburb}, merge: true);
    }

EDIT:
The method gets called by a listener on a `textfield`. This future is the future for the FutureBuilder.


    void inputListener() {
        if (_controller.text.length == 4) {
          query = _controller.text;
          setState(() {
            future = getData(query);
            _controller.clear();
            FocusScope.of(context).unfocus();
          });
        }
      }
EDIT
FutureBuilder(
                    future: future,
                    builder: (context, snapshot) {
                      if (snapshot.connectionState == ConnectionState.waiting) {
                        return CircularProgressIndicator();
                      } else if (snapshot.hasData) {
                        return (Text(snapshot.data));
                      }
                      return Text('no postcode');
                    }),

0 个答案:

没有答案