颤振中的位置

时间:2020-03-23 03:08:46

标签: http flutter dart http-post

我需要将该位置发送到我的数据库,但是它不起作用。我设法在屏幕上显示了它,但是什么也没发。

  1. location_service.dart(我正尝试通过邮寄发送)。
class LocationService {
  UserLocation _currentLocation;
  Location location = Location();

  StreamController<UserLocation> _locationController =
    StreamController<UserLocation>.broadcast();

  LocationService() {
    location.requestPermission().then((granted) {
      if(granted != null) {
        location.onLocationChanged().listen((locationData) {
          if(locationData != null){
            _locationController.add(UserLocation(
              latitude: locationData.latitude,
              longitude: locationData.longitude,
            ));
          }
        });
      }
    });
  }

  Stream<UserLocation> get locationStream => _locationController.stream;

  Future<UserLocation> getLocation() async {
    try {

      var userLocation = await location.getLocation();
      _currentLocation = UserLocation(
        latitude: userLocation.latitude, 
        longitude: userLocation.longitude,
        );
      const url = 'site';
      var map = new Map<String, dynamic>();
      map['api_key'] = 'MyApi';
      map['usuario'] = 'usuario@gmail.com';
      map['codigo'] = 'AAA-0000';
      map['latitude'] = '${userLocation?.latitude}';
      map['longitude'] = '${userLocation?.longitude}';
      map['data_hora'] = DateTime.now();

      http.Response response = await http.post(url, body: map,);

      print(response);

    }
    catch(e) {

      print('Could not get the location $e');

    }

    return _currentLocation;
  }
}
  1. location_view.dart(在这里,我可以在屏幕上显示)。
class LocationView extends StatelessWidget {
  const LocationView({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var userLocation = Provider.of<UserLocation>(context);
    return Center(
      child: Text(
          'Location: Lat${userLocation?.latitude}, Long: ${userLocation?.longitude}'),
    );


  }
}
  1. main.dart
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return StreamProvider<UserLocation>(
      builder: (context) => LocationService().locationStream,
      child: MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: LocationView(),
      ),
    );
  }
}

我与邮递员进行了测试,并且php文件一切正常。

1 个答案:

答案 0 :(得分:0)

您所犯的错误是传递给body参数(而不是传递)的地图的数据类型。您需要创建一个地图Map map = map<String, String>();

根据要传递的字符串类型,如果数据复杂,则需要传递适当的编码。

这本身就是http文档的一部分。

/// Sends an HTTP POST request with the given headers and body to the given URL,
/// which can be a [Uri] or a [String].
///
/// [body] sets the body of the request. It can be a [String], a [List<int>] or
/// a [Map<String, String>]. If it's a String, it's encoded using [encoding] and
/// used as the body of the request. The content-type of the request will
/// default to "text/plain".
///
/// If [body] is a List, it's used as a list of bytes for the body of the
/// request.
///
/// If [body] is a Map, it's encoded as form fields using [encoding]. The
/// content-type of the request will be set to
/// `"application/x-www-form-urlencoded"`; this cannot be overridden.
///
/// [encoding] defaults to [utf8].
///
/// For more fine-grained control over the request, use [Request] or
/// [StreamedRequest] instead.
Future<Response> post(url,
        {Map<String, String> headers, body, Encoding encoding}) =>
    _withClient((client) =>
        client.post(url, headers: headers, body: body, encoding: encoding));