getLocation()
Код: Выделить всё
Future getLocation() async {
bool serviceEnabled;
PermissionStatus permissionGranted;
LocationData locationData;
// Check if location services are enabled.
final Location location = Location();
serviceEnabled = await location.serviceEnabled();
if (!serviceEnabled) {
serviceEnabled = await location.requestService();
if (!serviceEnabled) {
return const LatLng(0, 0);
}
}
// Request permission to access location.
permissionGranted = await location.hasPermission();
if (permissionGranted == PermissionStatus.denied) {
permissionGranted = await location.requestPermission();
if (permissionGranted != PermissionStatus.granted) {
return const LatLng(0, 0);
}
}
// Get the current location.
locationData = await location.getLocation();
return LatLng(locationData.latitude!, locationData.longitude!);
}
https://riverpod.dev/docs/concepts/scop ... async-apis в В разделе Инициализация синхронного поставщика для асинхронных API я попытался получить местоположение в асинхронном основном приложении, прежде чем переопределить своего поставщика местоположения в RunApp. Область действия поставщика
Вот соответствующая часть основного
Код: Выделить всё
Future main() async {
const String envFile =
String.fromEnvironment('API_ENV', defaultValue: 'None Found');
debugPrint(
'Current Server: ${envFile == '.env.test' ? 'Ngrok' : 'Brian\'s'} Server ');
await dotenv.load(fileName: envFile);
LatLng location;
try {
location = await getLocation();
} catch (e) {
debugPrint("Error fetching initial location: $e");
location = const LatLng(0, 0);
}
runApp(ProviderScope(overrides: [
locationProvider.overrideWith(() {
debugPrint("Location Provider starts with: $location");
Location locationNotifier = Location();
debugPrint(locationNotifier.toString());
locationNotifier.updateLatLng(location);
return locationNotifier;
}),
], child: const MyApp()));
}
Код: Выделить всё
@riverpod
class Location extends _$Location {
// This is the "build" method required by @riverpod
@override
LatLng build() {
debugPrint("Building Location Provider");
ref.keepAlive();
return const LatLng(0, 0);
}
// Method to update the LatLng state
void updateLatLng(LatLng location) {
debugPrint("Updating Location to $location");
state = location;
}
}
из этого стека трассировки.
Код: Выделить всё
════════ Exception caught by widgets library ═══════════════════════════════════
The following LateError was thrown building MapPage(dirty, dependencies: [UncontrolledProviderScope], state: _MyHomePageState#dfd11):
LateInitializationError: Field '_element@65511105' has not been initialized.
The relevant error-causing widget was:
MapPage MapPage:file:///C:/Users/phili/Documents/palatte/lib/main.dart:78:19
When the exception was thrown, this was the stack:
#1 _ProviderStateSubscription.read (package:riverpod/src/framework/provider_base.dart:181:28)
provider_base.dart:181
#2 ConsumerStatefulElement.watch (package:flutter_riverpod/src/consumer.dart:568:8)
consumer.dart:568
#3 _MyHomePageState.build (package:stack_pratice/Screens/map_page/map_page.dart:250:27)
map_page.dart:250
#4 StatefulElement.build (package:flutter/src/widgets/framework.dart:5743:27)
framework.dart:5743
#5 ConsumerStatefulElement.build (package:flutter_riverpod/src/consumer.dart:539:20)
consumer.dart:539
#6 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5631:15)
framework.dart:5631
#7 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:5794:11)
framework.dart:5794
#8 Element.rebuild (package:flutter/src/widgets/framework.dart:5347:7)
framework.dart:5347
#9 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:5613:5)
framework.dart:5613
#10 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:5785:11)
framework.dart:5785
#11 ComponentElement.mount (package:flutter/src/widgets/framework.dart:5607:5)
framework.dart:5607
... Normal element mounting (228 frames)
Вот соответствующие части моей главной страницы (страницы карты)< /p>
Код: Выделить всё
class MapPage extends ConsumerStatefulWidget {
const MapPage({super.key});
@override
ConsumerState createState() => _MyHomePageState();
}
class _MyHomePageState extends ConsumerState
with SingleTickerProviderStateMixin {
...
@override
void initState() {
super.initState();
}
...
@override
Widget build(BuildContext context) {
LatLng location = ref.watch(locationProvider);
...
Это код моего приложения
Код: Выделить всё
class MyApp extends StatelessWidget {
const MyApp({super.key});
// MyApp is the base of the Palatte Mobile App
@override
Widget build(BuildContext context) {
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
statusBarColor: Colors.white, // Set status bar color
statusBarIconBrightness: Brightness.dark, // Set status bar icon color
));
return MaterialApp(
title: 'Palatte',
theme: ThemeData(
// This is the theme of your application.
// update to maintain consistent theming from color scheme
// to font sizing and typing
scaffoldBackgroundColor: Colors.grey[200],
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
dialogTheme: const DialogTheme(
surfaceTintColor: Colors.transparent,
),
),
// This is the landing page when
//you open up the app and the bottom of any navigation stack\
home: const MapPage(),
...
У меня нет идей. Я могу опубликовать все свои файлы, но моя страница карты в настоящее время представляет собой беспорядок и содержит около 500 строк кода, а это совсем другая проблема.
Какой совет?
Подробнее здесь: https://stackoverflow.com/questions/793 ... r-that-was