如何在OnPressed中调用多个函数

时间:2020-02-06 12:23:06

标签: flutter dart flutter-layout flutter-dependencies flutter-test

Positioned(
          bottom: 25,
          right: 10,
          child: FloatingActionButton(
              heroTag: 'tag1',
              backgroundColor: Colors.white.withOpacity(0.7),
              child: Icon(
                Icons.location_searching,
                color: Colors.purple,
              ),
              onPressed: () {
                _addGeoPoint();
                _animateToUser();
              }),
        ),

仅_animateToUser工作

_animateToUser() async {
    var pos = await location.getLocation();
    mapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
        target: LatLng(pos.latitude, pos.longitude), zoom: 17.0)));
  }

_addGeoPoint无法正常工作

Future<DocumentReference> _addGeoPoint() async {
    var pos = await location.getLocation();
    final coordinates = Coordinates(pos.latitude, pos.longitude);
    var addresses =
        await Geocoder.local.findAddressesFromCoordinates(coordinates);
    var first = addresses.first;
    print("${first.featureName} : ${first.addressLine}");
//    GeoFirePoint point =
//        geo.point(latitude: pos.latitude, longitude: pos.longitude);
    return _firestore.collection('location').add({
      'UserLocation': first.featureName,
      'UserLocationName': first.addressLine
    });
  }

但是当我更改onPressed到

onPressed: _addGeopoint,

_addGeopoint有效。

我不能一次调用这两个函数。

1 个答案:

答案 0 :(得分:0)

当您在函数内部使用async和wait时,需要将try / catch以及return语句放入catch中。万一发生任何异常或由于其他一些原因而导致它无法继续前进,它将不会调用第二个函数。请检查以下示例。

onPressed: () {
     _funOne();
     _funTwo();
}),


_funOne() async{
  try {
    await location.getLocation()(); 
    // your code...
  } catch (e) {
    return;
  }
}

_funTwo() async{
  try {
    await location.getLocation()(); 
    // your code...
  } catch (e) {
    return;
  }
}