我正在使用 Flutter 构建一个移动应用。
我想在登录时启用我的流提供程序并在我注销时禁用我的流。此外,即使我离开应用程序并转到另一个应用程序,我也想继续流传输 .流提供了电话位置。
现在,当我加载应用程序时,它会立即询问我是否要启用定位服务,然后当我启用它时,它会开始更新手机位置。
这是我的代码: main.dart
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider.value(
value: Auth(),
),
StreamProvider.value(
value: LocationService().locationStream,
),
],
child: Consumer<Auth>(
builder: (ctx, auth, _) => MaterialApp(
title: 'deee',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: auth.isAuth ? TabsScreen() : LoginPage(),
initialRoute: "/",
// onGenerate routes and unknown routes "/": (ctx) => TabsScreen(),
routes: {
},
),
),
);
}
}
location_service.dart
import 'dart:async';
import 'dart:convert';
import 'package:location/location.dart';
import '../models/user_location.dart';
import '../providers/auth.dart';
import 'package:http/http.dart' as http;
class LocationService {
// Keep track of current Location
UserLocation _currentLocation;
Location location = Location();
Auth auth = Auth();
int counter = 1;
// Continuously emit location updates
StreamController<UserLocation> _locationController =
StreamController<UserLocation>.broadcast();
LocationService() {
location.requestPermission().then((granted) {
if (granted == PermissionStatus.granted) {
location.onLocationChanged.listen((locationData) async {
if (locationData != null) {
var firebaseId = auth.firebaseId;
if (firebaseId != null) {
try {
final url =
'https://delivery-system-default-rtdb.firebaseio.com/Drivers/${firebaseId}.json';
await http.patch(url,
body: jsonEncode({
'lat': locationData.latitude,
'lng': locationData.longitude,
'status': true
}));
} catch (error) {
print("error");
print(error);
}
}
counter++;
_locationController.add(UserLocation(
latitude: locationData.latitude,
longitude: locationData.longitude,
));
}
});
}
});
}
Stream<UserLocation> get locationStream => _locationController.stream;
感谢您的时间和精力