我想根据网址内的纬度/经度获取当前用户位置以更新附近的商店。
但我无法弄清楚如何在两个不同的类之间交互数据。我想使它的工作类似'AppConfig.latitude = _position.latitude;'。我尝试了几种方法,包括我在stackoverflow和youtube上找到的继承小部件,但仍然无法正常工作。这绝对是我错过了什么。
当我使用一个集团时,我不知道如何使用bloc更新'class AppConfig'中的数据。可以简单地使用SetState吗?我昨天花了整整一天谷歌搜索这个问题。请指导我正确的方法
class _CurrentLocationState extends State<CurrentLocation> {
Position _position;
Future<void> _initPlatformState() async {
Position position;
try {
final Geolocator geolocator = Geolocator()
...
setState(() {
_position = position;
// print(${_position.latitude})
// 35.9341...
// print(${_position.longitude})
// -117.0912...
<*I want to make it work something like this*>
AppConfig.latitude = _position.latitude;
AppConfig.longitude = _position.longitude;
<*this is how I tried with bloc*>
latLongBloc.getUserLocation(LatLng(position.latitude, position.longitude));
});
<* latitude/longitude need to be updated with a current user location *>
abstract class AppConfig {
static const double latitude = 0;
static const double longitude = 0;
static const List<String> storeName = ['starbucks'];
}
<* I need to use AppConfig.latitude for url in Repository class*>
class Repository {
...
Future<List<Business>> getBusinesses() async {
String webAddress =
"https://api.yelp.com/v3/businesses/search?latitude=${AppConfig.latitude}&longitude=${AppConfig.longitude}&term=${AppConfig.storeName}";
...
}
这是我的bloc.dart文件
class LatLongBloc {
StreamController _getUserLocationStreamController = StreamController<LatLng>();
Stream get getUserLocationStream => _getUserLocationStreamController.stream;
dispose(){
_getUserLocationStreamController.close();
}
getUserLocation(LatLng userLatLong) {
_getUserLocationStreamController.sink.add(userLatLong);
}
}
final latLongBloc = LatLongBloc();
你想在类/小部件之间共享状态,对吧?还有其他国家管理模式,如ScopedModel
或Redux
。每种模式都有其优点和缺点,但如果您不理解它,则不必使用BLoC。
我建议使用ScopedModel
,因为在我看来这很容易理解。您的数据/状态位于中心位置,可以使用ScopedModel
访问。如果你不喜欢使用这种方法,那么尝试Redux
或其他模式:)
希望它能帮助你:D
你的Glup3