Расположение во флаттере - PullRequest
0 голосов
/ 23 марта 2020

Мне нужно отправить местоположение в мою базу данных, но оно не работает. Мне удалось показать его на экране, но ничего не отправлять.

  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;
  }
}
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}'),
    );


  }
}
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 голосов
/ 24 марта 2020

Ошибка, которую вы делаете - это тип данных карты, которую вы передаете аргументу тела (вы передаете вместо). Вам необходимо создать карту 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));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...