import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart' as lat;
import 'package:location/location.dart' as loc;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:mapbox_gl/mapbox_gl.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
//besafe
late SharedPreferences sharedPreferences;
LatLng getCurrentLatLngFromSharedPrefs() {
return LatLng(sharedPreferences.getDouble('latitude')!,
sharedPreferences.getDouble('longitude')!);
}
void main() async{
runApp(const MyApp());
sharedPreferences =await SharedPreferences.getInstance();
const color2= Color(0xfb74093);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'BeSafe',
theme: ThemeData(
primarySwatch: Colors.pink,
),
home: const MyHomePage(title: 'BeSafe'),
debugShowCheckedModeBanner: false,
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late CameraPosition _initialCameraPosition;
late MapboxMapController controller;
static const List<String> imageList = [
"https://www.uber-assets.com/image/upload/f_auto,q_auto:eco,c_fill,w_1099,h_733/v1568070387/assets/b5/0a5191-836e-42bf-ad5d-6cb3100ec425/original/UberX.png",
"https://www.uber-assets.com/image/upload/f_auto,q_auto:eco,c_fill,w_956,h_537/v1569012661/assets/19/dea9bc-88d6-461e-a233-17ed4d8cdc09/original/Taxi.png",
"https://www.uber-assets.com/image/upload/f_auto,q_auto:eco,c_fill,w_956,h_537/v1571927853/assets/39/c1c2c7-61eb-4432-9bac-728b974207e7/original/cityscoot-icon-mobile.png"
];
void initState(){
super.initState();
initializeLocationandSave();
LatLng latlng= getCurrentLatLngFromSharedPrefs();
_initialCameraPosition=CameraPosition(target:latlng ,zoom:15);
print("he");
}
void initializeLocationandSave() async{
sharedPreferences = await SharedPreferences.getInstance();
loc.Location _location = loc.Location();
bool? _serviceEnabled;
loc.PermissionStatus? _permissionGranted;
_serviceEnabled = await _location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await _location.requestService();
}
_permissionGranted = await _location.hasPermission();
if (_permissionGranted == loc.PermissionStatus.denied) {
_permissionGranted = await _location.requestPermission();
}
print("yo");
loc.LocationData _locationData = await _location.getLocation(); print("bye");
sharedPreferences.setDouble('latitude',_locationData.latitude!);
sharedPreferences.setDouble('longitude',_locationData.latitude!);
LatLng currentlatlng= getCurrentLatLngFromSharedPrefs();
}
_onMapCreated(MapboxMapController controller) async {
this.controller=controller;
}
_onStyleLoadedCallback() async{
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Stack(
children: <Widget>[
MapboxMap(
accessToken: dotenv.env['MAPBOX_ACCESS_TOKEN'] ,initialCameraPosition: _initialCameraPosition,
onMapCreated: _onMapCreated,
onStyleLoadedCallback: _onStyleLoadedCallback,
myLocationEnabled: true,
myLocationTrackingMode: MyLocationTrackingMode.TrackingGPS,
minMaxZoomPreference: const MinMaxZoomPreference(14, 17),
),
new Positioned(
child:SizedBox(
height: 60,
),),
new Positioned(
child:
Padding(
padding:EdgeInsets.only(left:30,right:30,top:30),
child:
SizedBox(
height: 40,
child: TextField(
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(30.0),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(50.0),
borderSide: BorderSide(
width: 10),
),
fillColor: Colors.white24,
filled: true,
),
))
),
),
Padding(
padding:EdgeInsets.only(top: 556),
child: CarouselSlider(
options: CarouselOptions(
enlargeCenterPage: true,
enableInfiniteScroll: true,
height: 200,
autoPlay: true,
),
items: imageList.map((e) => ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Image.network(e,
width: 1050,
height: 300,
fit: BoxFit.cover,)
],
) ,
)).toList(),
),
),
] ,
),
);
}
}
程序无法运行,错误是NotIntialisedError,这让人很困惑。我认为这与.getLocation()或SharedPreferences变量有关。
我试着打印cout语句,显然,代码停在的一行是:loc.LocationData _locationData = await _location.getLocation();
错误:
The following NotInitializedError was thrown building MyHomePage(dirty, state: _MyHomePageState#9417a):
Instance of 'NotInitializedError'
The relevant error-causing widget was:
MyHomePage MyHomePage:file:///C:/Users/ali33/StudioProjects/besafe/lib/main.dart:35:19
When the exception was thrown, this was the stack:
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 251:49 throw_
packages/flutter_dotenv/src/dotenv.dart 42:7 get env
packages/besafe/main.dart 113:40 build
packages/flutter/src/widgets/framework.dart 4919:27 build
packages/flutter/src/widgets/framework.dart 4806:15 performRebuild
packages/flutter/src/widgets/framework.dart 4977:11 performRebuild
packages/flutter/src/widgets/framework.dart 4529:5 rebuild
1条答案
按热度按时间xwbd5t1u1#
我猜问题主要出在你身上:
必须在runApp之前调用,因为在小部件内部调用此变量时,它不会初始化。
用
runApp(const MyApp());
切换