Flutter: Geolocator gives wrong location - flutter

When I execute, (click on the "show Longitude and Latitude" button) I have two problems, a wrong position and an error:
**W/GooglePlayServicesUtil( 5181): com.example.geolocalisation_youtube requires the Google Play Store, but it is missing.
I/flutter ( 5181): 10681894.898369517
I/flutter ( 5181): long c.longitude
I/flutter ( 5181): 37.421998333333335
E/flutter ( 5181): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(IO_ERROR, A network error occurred trying to lookup the supplied coordinates (latitude: 37.421998, longitude: -122.084000)., null, null)
E/flutter ( 5181): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:653:7)
E/flutter ( 5181): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:296:18)
E/flutter ( 5181): <asynchronous suspension>
E/flutter ( 5181): #2 MethodChannelGeocoding.placemarkFromCoordinates (package:geocoding_platform_interface/src/implementations/method_channel_geocoding.dart:56:24)
E/flutter ( 5181): <asynchronous suspension>
E/flutter ( 5181): #3 _MyHomePageState.build.<anonymous closure> (package:geolocalisation_youtube/main.dart:84:47)
E/flutter ( 5181): <asynchronous suspension>
**
Here’s the code:
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:geocoding/geocoding.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future getPosition() async{
bool service= await Geolocator.isLocationServiceEnabled();
LocationPermission per= await Geolocator.checkPermission();
if (per==LocationPermission.denied){
per= await Geolocator.requestPermission();
if(per!=LocationPermission.denied){
}
}
print(service);
print("---------------");
print(per);
print("---------------");
if(!service ){
AwesomeDialog(
context: context,
title: "services",
body:
Text("service is enabled")
)..show();
}
}
Future <Position> getLatandLong() async{
return await Geolocator.getCurrentPosition().then((value) => value);
}
#override
void initState(){
getPosition();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children: [
Container(
height: 500,
width:400 ,
),
ElevatedButton(
onPressed: () async{
var c = await getLatandLong();
var distance= await Geolocator.distanceBetween(c.latitude, c.longitude, 28.033886, 1.659626);
print(distance);
print("long c.longitude ");
print(c.latitude);
List<Placemark> placemarks = await placemarkFromCoordinates(c.latitude, c.longitude);
print(placemarks[0].administrativeArea);
},
child: Text(" show Longitude and Latitude"))
],
),
);
}
}
I got this error on the latest version of Android Studio.

Related

Flutter Error: StackOverflowError was thrown building Consumer<LocationProvider>(dirty, dependencies: [_InheritedProviderScope<LocationProvider?>])

i'm trying to include live location tracking into my app using the following packages:
google_maps_flutter 2.1.2 --> https://pub.dev/packages/google_maps_flutter/install
location 4.3.0 --> https://pub.dev/packages/location
provider 6.0.2 --> https://pub.dev/packages/provider
I am receiving the following error:
════════ Exception caught by widgets library ═══════════════════════════════════
The following StackOverflowError was thrown building Consumer<LocationProvider>(dirty, dependencies: [_InheritedProviderScope<LocationProvider?>]):
Stack Overflow
The relevant error-causing widget was
Consumer<LocationProvider>
lib/google_map_page.dart:31
When the exception was thrown, this was the stack
#0 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#1 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#2 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#3 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#4 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#5 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#6 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#7 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#8 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#9 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#10 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#11 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#12 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#13 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#14 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#15 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#16 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#17 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#18 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#19 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#20 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#21 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#22 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#23 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#24 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#25 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
#26 LocationProvider.locationPosition
package:map_test/provider/location_provider.dart:55
......
package:map_test/provider/location_provider.dart:55 -->
LatLng get locationPosition => locationPosition;
There is 3 classes:
main.dart
google_map_page.dart
location_provider.dart
1. main.dart
import 'package:flutter/material.dart';
import 'package:map_test/google_map_page.dart';
import 'package:map_test/provider/location_provider.dart';
import 'package:provider/provider.dart';
void main() {
runApp(const MyApp());
}
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 MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => LocationProvider(),
child: const GoogleMapPage(),
)
],
child: MaterialApp(
title: 'Flutter Demo',
home: const GoogleMapPage(),
),
);
}
}
2. google_map_page.dart
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:map_test/provider/location_provider.dart';
import 'package:provider/provider.dart';
class GoogleMapPage extends StatefulWidget {
const GoogleMapPage({Key? key}) : super(key: key);
#override
State<GoogleMapPage> createState() => _GoogleMapPageState();
}
class _GoogleMapPageState extends State<GoogleMapPage> {
#override
void initState() {
super.initState();
Provider.of<LocationProvider>(context, listen: false).initalization();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Map2'),
backgroundColor: Colors.red,
),
body: googleMapUI());
}
Widget googleMapUI() {
return Consumer<LocationProvider>(builder: (consumerContext, model, child) {
if (model.locationPosition != null) {
return Column(
children: [
Expanded(
child: GoogleMap(
mapType: MapType.normal,
initialCameraPosition:
CameraPosition(target: model.locationPosition, zoom: 18),
myLocationEnabled: true,
myLocationButtonEnabled: true,
onMapCreated: (GoogleMapController controller) {},
),
)
],
);
}
return Container(
child: Center(
child: CircularProgressIndicator(),
),
);
});
}
}
3.location_provider.dart
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
class LocationProvider with ChangeNotifier {
// Widget loc() {
// throw '';
// }
bool locationServiceActive = true;
LocationProvider() {
Location location;
location = new Location();
}
Location get location => location;
initalization() async {
await getUserLocation();
}
getUserLocation() async {
bool _serviceEnabled;
PermissionStatus _permissionGranted;
LatLng locationPosition;
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
return;
}
}
_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
location.onLocationChanged.listen((LocationData currentLocation) {
locationPosition = LatLng(
currentLocation.latitude!,
currentLocation.longitude!,
);
print(locationPosition);
notifyListeners();
});
}
LatLng get locationPosition => locationPosition; // line 55
}
It's my first time coding in flutter, i faced a lot of problem because of the Null Safety already. it just seems like the problems are endless.
any recommendations will be much appreciated.
Thank you.
The StackOverflowError is caused by self reference
LatLng get locationPosition => locationPosition;
means locationPosition is itself.
Hence will suggest you to amend the internal parameter variable by having prefix _
LatLng get locationPosition => _locationPosition;
while your class params and constructor can be written like below
class LocationProvider with ChangeNotifier {
LatLng? _locationPosition;
final Location _location = new Location();
LocationProvider();
Location get location => _location;
LatLng? get locationPosition => _locationPosition;
// other parts
}
I am not sure but try to wrap consumer in build method
Like this:
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Map2'),
backgroundColor: Colors.red,
),
body: Consumer<LocationProvider>(builder: (consumerContext, model, child) {
return googleMapUI()});
}
And add needed parameters

FLUTTER ERROR: Unhandled Exception: 'package:flutter_downloader/src/downloader.dart'

I've a flutter program which downloads a file by using a URL using the flutter_downloader package.I hace a button where on click will download the file.
Below is my implementation
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await FlutterDownloader.initialize(
debug: true
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page',key: GlobalKey(),),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({required Key key, required this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(height: 60,),
FlatButton(
child: Text("Start Downloading"),
color: Colors.redAccent,
textColor: Colors.white,
onPressed: () async {
final status = await Permission.storage.request();
if (status.isGranted) {
final externalDir = await getExternalStorageDirectory();
final id = await FlutterDownloader.enqueue(
url: "https://firebasestorage.googleapis.com/v0/b/storage-3cff8.appspot.com/o/2020-05-29%2007-18-34.mp4?alt=media&token=841fffde-2b83-430c-87c3-2d2fd658fd41",
savedDir: externalDir!.path,
fileName: "download",
showNotification: true,
openFileFromNotification: true,
);
} else {
print("Permission deined");
}
},
)
],
),
),
);
}
}
The error massage I get when the button is pressed is,
E/flutter (21960): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception:
'package:flutter_downloader/src/downloader.dart': Failed assertion: line 80 pos 12:
'_initialized': FlutterDownloader.initialize() must be called first
E/flutter (21960): #0 _AssertionError._doThrowNew (dart:core-
patch/errors_patch.dart:46:39)
E/flutter (21960): #1 _AssertionError._throwNew (dart:core-
patch/errors_patch.dart:36:5)
E/flutter (21960): #2 FlutterDownloader.enqueue
(package:flutter_downloader/src/downloader.dart:80:12)
E/flutter (21960): #3 _MyHomePageState.build.<anonymous closure>
(package:care_giver_app/functions_test.dart:102:54)
E/flutter (21960): <asynchronous suspension>
E/flutter (21960):
If im not wrong,it states that I have to initialize flutter_downloader first but I've already done that in line No.06-No.09 in the implementation above.
I've provided the necessary providers in the AndroidManifest file as well
<provider
android:name="vn.hunghd.flutterdownloader.DownloadedFileProvider"
android:authorities="${applicationId}.flutter_downloader.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
android:exported="false"
tools:node="merge">
<meta-data
android:name="androidx.work.WorkManagerInitializer"
android:value="androidx.startup"
tools:node="remove" />
</provider>
<!-- declare customized Initializer -->
<provider
android:name="vn.hunghd.flutterdownloader.FlutterDownloaderInitializer"
android:authorities="${applicationId}.flutter-downloader-init"
android:exported="false">
<!-- changes this number to configure the maximum number of concurrent tasks -->
<meta-data
android:name="vn.hunghd.flutterdownloader.MAX_CONCURRENT_TASKS"
android:value="5" />
</provider>

Show snackbar message after widget rebuild

I try to do login page (do the transaction in some Future function) and show the error message by Snackbar.
Click login
Show loading
Future transaction done (back to original page), and then show the error message
Here is the flow I want to achieve (the last part failed):
I don't know how to show the snackBar correctly using the message from future.
showSnackBar need BuildContext but the context inside the signIn page seems no longer valid anymore after the message come back from Future.
I am now using package flutter_hooks and hooks_riverpod for the state management.
My State
class MyState{
MyState({this.data,this.isLoading});
final bool isLoading;
final String data;
MyState copyWith({data, isLoading}) => MyState(data: data, isLoading: isLoading);
}
State control and provider
Future<String> getData() fetch data and return error message
class MyStateNotifier extends StateNotifier<MyState> {
MyStateNotifier(MyState state) : super(state);
Future<String> getData() async {
state = state.copyWith(isLoading: true);
await Future.delayed(Duration(seconds: 3)); // simulate getting data
state = state.copyWith(isLoading: false, data: 'some data');
return 'error message';
}
}
final myStateProvider = StateNotifierProvider<MyStateNotifier>((ref) {
return MyStateNotifier(MyState(data: null, isLoading: false));
});
My widget
myState.isLoading: show loading page or sign in page
class WidgetA extends HookWidget {
const WidgetA({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
final myState = useProvider(myStateProvider.state);
return Center(
child: myState.isLoading ? CircularProgressIndicator() : SignInPage(),
);
}
}
class SignInPage extends HookWidget {
const SignInPage({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: () async {
context.read(myStateProvider).getData().then(
(message) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
},
);
},
child: Text('login'),
);
}
}
I use showSnackBar inside then after getData(), but it show the error message:
E/flutter ( 6869): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Looking up a
deactivated widget's ancestor is unsafe.
E/flutter ( 6869): At this point the state of the widget's element tree is no longer stable.
E/flutter ( 6869): To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.
E/flutter ( 6869): #0 Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure> (package:flutter/src/widgets/framework.dart:3938:9)
E/flutter ( 6869): #1 Element._debugCheckStateIsActiveForAncestorLookup (package:flutter/src/widgets/framework.dart:3952:6)
E/flutter ( 6869): #2 Element.findAncestorWidgetOfExactType (package:flutter/src/widgets/framework.dart:4044:12)
E/flutter ( 6869): #3 debugCheckHasScaffoldMessenger.<anonymous closure> (package:flutter/src/material/debug.dart:142:17)
E/flutter ( 6869): #4 debugCheckHasScaffoldMessenger (package:flutter/src/material/debug.dart:154:4)
E/flutter ( 6869): #5 ScaffoldMessenger.of (package:flutter/src/material/scaffold.dart:218:12)
E/flutter ( 6869): #6 SignInPage.build.<anonymous closure>.<anonymous closure> (package:flutter_app_test2/main.dart:171:35)
E/flutter ( 6869): #7 _rootRunUnary (dart:async/zone.dart:1198:47)
E/flutter ( 6869): #8 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 6869): #9 _FutureListener.handleValue (dart:async/future_impl.dart:143:18)
E/flutter ( 6869): #10 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:696:45)
E/flutter ( 6869): #11 Future._propagateToListeners (dart:async/future_impl.dart:725:32)
E/flutter ( 6869): #12 Future._completeWithValue (dart:async/future_impl.dart:529:5)
E/flutter ( 6869): #13 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:254:13)
E/flutter ( 6869): #14 MyStateNotifier.getData (package:flutter_app_test2/main.dart)
E/flutter ( 6869): <asynchronous suspension>
You can copy paste run full code below
Reason : Because SignInPage disappear after click login button
Quick fix is use ScaffoldMessenger and provide scaffoldMessengerKey then call scaffoldMessengerKey.currentState.showSnackBar(SnackBar(content: Text(message)));
code snippet
final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey =
GlobalKey<ScaffoldMessengerState>();
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ScaffoldMessenger(
key: scaffoldMessengerKey,
child: Scaffold(
...
context.read(myStateProvider).getData().then(
(message) {
scaffoldMessengerKey.currentState
.showSnackBar(SnackBar(content: Text(message)));
},
);
working demo
full code
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hooks_riverpod/all.dart';
class MyState {
MyState({this.data, this.isLoading});
final bool isLoading;
final String data;
MyState copyWith({data, isLoading}) =>
MyState(data: data, isLoading: isLoading);
}
class MyStateNotifier extends StateNotifier<MyState> {
MyStateNotifier(MyState state) : super(state);
Future<String> getData() async {
state = state.copyWith(isLoading: true);
await Future.delayed(Duration(seconds: 3)); // simulate getting data
state = state.copyWith(isLoading: false, data: 'some data');
return 'error message';
}
}
final myStateProvider = StateNotifierProvider<MyStateNotifier>((ref) {
return MyStateNotifier(MyState(data: null, isLoading: false));
});
void main() {
runApp(
const ProviderScope(child: MyApp()),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(home: Home());
}
}
final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey =
GlobalKey<ScaffoldMessengerState>();
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ScaffoldMessenger(
key: scaffoldMessengerKey,
child: Scaffold(
appBar: AppBar(title: const Text('example')),
body: WidgetA(),
),
);
}
}
class WidgetA extends HookWidget {
const WidgetA({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
final myState = useProvider(myStateProvider.state);
return Center(
child: myState.isLoading ? CircularProgressIndicator() : SignInPage(),
);
}
}
class SignInPage extends HookWidget {
const SignInPage({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: () async {
context.read(myStateProvider).getData().then(
(message) {
scaffoldMessengerKey.currentState
.showSnackBar(SnackBar(content: Text(message)));
},
);
},
child: Text('login'),
);
}
}
You'll have to await you getData() request and return the message in a variable, then call the snackbar. You're trying to call the snackbar inside the future call. This can't be done on the UI.
final message = await context.read(myStateProvider).getData();
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));

Unable to call Material page route in state class with async delay

I am trying to display a splash screen for a few seconds then trying to navigate it to the next screen but I am getting this error. Probably because of accessing context in iniState methods but I am also using async so I don't think there's should be any issue.
E/flutter ( 6663): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: NoSuchMethodError: The method 'findAncestorStateOfType' was called on null.
E/flutter ( 6663): Receiver: null
E/flutter ( 6663): Tried calling: findAncestorStateOfType<NavigatorState>()
E/flutter ( 6663): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter ( 6663): #1 Navigator.of
package:flutter/…/widgets/navigator.dart:2185
import 'package:awsomeNotes/appUtilities/dimensions.dart';
import 'package:awsomeNotes/views/phoneAuthPage/phoneAuthPage.dart';
import 'package:flutter/material.dart';
class SplashScreen extends StatefulWidget {
#override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
nextPage() async {
await Future.delayed(Duration(seconds: 5));
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PhoneAuthPage(),
),
);
}
#override
void initState() {
nextPage();
super.initState();
}
#override
Widget build(BuildContext context) {
Dimensions(context);
return Material(
child: Center(
child: Text(
"This is Splash Screen",
style: TextStyle(fontSize: Dimensions.boxHeight * 5),
),
),
);
}
}
I am navigating to the next page but with the error specified.

How do you use the flutter/dart package spreadsheet_decoder?

When I try to use the package 'spreadsheet_decoder' in my flutter app like so:
var file = Uri.file('spreadsheets/Contact_list.xlsx');
var bytes = File.fromUri(file).readAsBytesSync();
var decoder = SpreadsheetDecoder.decodeBytes(bytes);
where I created a folder called spreadsheets inside the app and added it to the pubspec.
I got the following error:
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: FileSystemException: Cannot open file, path = 'spreadsheets/Contact_list.xlsx' (OS Error: No such file or directory, errno = 2)
#0 _File.throwIfError (dart:io/file_impl.dart:645:7)
#1 _File.openSync (dart:io/file_impl.dart:489:5)
#2 _File.readAsBytesSync (dart:io/file_impl.dart:549:18)
#3 getData (package:cvr/extract_excel.dart:8:34)
#4 _TransferScreenState.transferPeopleFromExcelToFirebase (package:cvr/utilities/transfer_data.dart:35:5)
<asynchronous suspension>
#5 _TransferScreenState.build.<anonymous closure> (package:cvr/utilities/transfer_data.dart:52:11)
#6 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
#7 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
#8 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
#9 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.<…>
If I use the exact same code in a stand alone dart file and run it separately I do not get this error.
Does anyone know where I can save the excel document and what path I should use to access it?
You can use https://pub.dev/packages/path_provider and get temp directory via getTemporaryDirectory()
You can copy paste run full code below
and need to put your file in /data/user/0/your_domain.your_project/cache/test.xlsx
code snippet
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
var file = '${tempDir.path}/test.xlsx';
print('file full path $file');
var bytes = File(file).readAsBytesSync();
var decoder = SpreadsheetDecoder.decodeBytes(bytes, update: true);
output of full code
I/flutter ( 515): file full path /data/user/0/your_domain.your_proejct/cache/test.xlsx
I/flutter ( 515): wosksheet1
I/flutter ( 515): 1
I/flutter ( 515): 2
I/flutter ( 515): [test]
I/flutter ( 515): [123]
full code
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:spreadsheet_decoder/spreadsheet_decoder.dart';
import 'package:path_provider/path_provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() async {
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
var file = '${tempDir.path}/test.xlsx';
print('file full path $file');
var bytes = File(file).readAsBytesSync();
var decoder = SpreadsheetDecoder.decodeBytes(bytes, update: true);
for (var table in decoder.tables.keys) {
print(table);
print(decoder.tables[table].maxCols);
print(decoder.tables[table].maxRows);
for (var row in decoder.tables[table].rows) {
print("$row");
}
setState(() {
_counter++;
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Try using the Uri.parse or Uri.tryParse mehod
Example Code:
var readbytes = File.fromUri(Uri.parse('path/THISisCOOL.xlsx')).readAsBytesSync();