Расстояние между пользователями всегда равно 0, хотя координаты во флаттере разные? - PullRequest
0 голосов
/ 13 июля 2020

Я пытаюсь показать расстояние между несколькими пользователями, которые зарегистрированы в приложении и отображаются в Listview, а код для Listview приведен ниже: -

class DistanceListView extends StatefulWidget {
  @override
  _DistanceListViewState createState() => _DistanceListViewState();
}

class _DistanceListViewState extends State<DistanceListView> {
  @override
  Widget build(BuildContext context) {
    final profiles = Provider.of<List<ProfileData>>(context) ?? [];
    return ListView.builder(
        itemCount: profiles.length,
        itemBuilder: (context, index) {
          return DistanceCard(profile: profiles[index], index: index);
        });
  }
}

Где profiles - это список, содержащий все местоположения пользователей в нем. Прямо сейчас я создал двух фиктивных пользователей с координатами 35.6762, 139.6503 и 6.9271, 79.8612 .

Код для DistanceCard выглядит следующим образом: -

class DistanceCard extends StatefulWidget {
  final int index;
  final ProfileData profile;
  DistanceCard({this.index, this.profile});
  @override
  _DistanceCardState createState() => _DistanceCardState();
}

class _DistanceCardState extends State<DistanceCard> {
  @override
  Widget build(BuildContext context) {
    final profiles = Provider.of<List<ProfileData>>(context) ?? [];
    final longitude = widget.profile.location.longitude;
    final latitude = widget.profile.location.latitude;
    var distance;

    futureconvert() async {
      distance = await Geolocator().distanceBetween(
          longitude,
          latitude,
          profiles[widget.index].location.longitude,
          profiles[widget.index].location.latitude);
      return distance;
    }

    return FutureBuilder(
        future: futureconvert(),
        builder: (context, snapshot) {
          return Card(
            child: Center(
              child: Padding(padding: EdgeInsets.all(5),
               child: Text(distance)),
            ),
          );
        });
  }
}

Вот проблема, когда виджет отображается, distance всегда отображается как 0,0 . Кто-нибудь может указать, где я ошибся?

Ответы [ 2 ]

1 голос
/ 13 июля 2020

Хорошо, сначала позвольте мне указать на ошибку , которую вы делаете.

Вы пытаетесь найти расстояние между теми же координатами,

позвольте мне объяснить.

Вы передаете 2 параметра в карту расстояний.

  • Профиль [индекс]
  • индекс
return DistanceCard(profile: profiles[index], index: index);

хорошо?

Теперь в Distance Card вы используете Provider для получения точно такой же широты профиля и длины профиля из списка профилей здесь.

 distance = await Geolocator().distanceBetween(
          longitude,
          latitude,
          profiles[widget.index].location.longitude,
          profiles[widget.index].location.latitude);
      return distance;
    }

Что здесь означает «широта»? -> profile [index] .location.latitude

а другой пункт? -> profiles [widget.index] .location.latitude

Поскольку индекс такой же, вы получаете тот же самый объект, следовательно, 0.0 - это расстояние.

I рекомендовал бы сделать одну фиксированную координату « якорь », например текущее местоположение пользователя или местоположение любого пользователя, а затем найти относительные местоположения.

Дайте мне знать если это исправило вашу ошибку.

0 голосов
/ 13 июля 2020

Вы в основном используете один и тот же объект дважды, поэтому расстояние от него равно 0

return DistanceCard(profile: profiles[index], index: index)
// You're passing the profile, let's say at index 0 of your list

Затем в _DistanceCardState (который я рекомендую вам создать этот код вне метода сборки)

final profiles = Provider.of<List<ProfileData>>(context) ?? []; //This is the Provider that has the same list you used to build the DistanceCard
final longitude = widget.profile.location.longitude; //The longitude of the profile at index 0
final latitude = widget.profile.location.latitude; //The latitude of the profile at index 0
var distance;

futureconvert() async {
  distance = await Geolocator().distanceBetween(
      longitude,
      latitude,
      profiles[widget.index].location.longitude, //this and longitude refers to the same value (index 0 for the first one)
      profiles[widget.index].location.latitude); //this and latitude refers to the same value (index 0 for the first one)
  return distance;
}

И так далее при итерации по списку. Вопрос в том, с кем именно вы хотите это сравнить? Все остальные Profiles в Списке? Следующий в списке?

class _DistanceCardState extends State<DistanceCard> {
  List<ProfileData> profiles;
  var distance;

  @override
  didChangeDependencies(){
    super.didchangeDependencies();
    profiles = Provider.of<List<ProfileData>>(context) ?? [];
  }

    futureconvert() async {
      int anotherIndex = 0;
      if(profiles.length != widget.index) anotherIndex = widget.index + 1;
      //This will compare it to the next profile in the list
      distance = await Geolocator().distanceBetween(
          widget.profile.location.longitude,
          widget.profile.location.latitude,
          profiles[anotherIndex].location.longitude, //Give another longitude
          profiles[anotherIndex].location.latitude); //Give another latitude
      return distance;
    }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: futureconvert(),
        builder: (context, snapshot) {
          return Card(
            child: Center(
              child: Padding(padding: EdgeInsets.all(5),
               child: Text(distance)),
            ),
          );
        });
  }
}
...