Error using path\_provider package in flutter

Issue

I am trying to get the application documents directory using the path_provider package in flutter. I am using the hive database and so I need the path.

Here’s my code:

void main() async {
  final appDocsDir  await getApplicationDocumentsDirectory(); //error is on this line
  Hive.init(appDocsDir.path);
  runApp(MyApp());
}

I am getting this error:

E/flutter (18811): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value
E/flutter (18811): #0      MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:142:86)
E/flutter (18811): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:148:36)
E/flutter (18811): #2      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:331:12)
E/flutter (18811): #3      MethodChannelPathProvider.getApplicationDocumentsPath (package:path_provider_platform_interface/src/method_channel_path_provider.dart:50:10)
E/flutter (18811): #4      getApplicationDocumentsDirectory (package:path_provider/path_provider.dart:138:40)
E/flutter (18811): #5      main (package:my_app/main.dart:9:28)
E/flutter (18811): #6      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:142:25)
E/flutter (18811): #7      _rootRun (dart:async/zone.dart:1354:13)
E/flutter (18811): #8      _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (18811): #9      _runZoned (dart:async/zone.dart:1789:10)
E/flutter (18811): #10     runZonedGuarded (dart:async/zone.dart:1777:12)
E/flutter (18811): #11     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:138:5)
E/flutter (18811): #12     _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
E/flutter (18811): #13     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
E/flutter (18811): 

I am running the app on an android device connected through usb (Using flutter run). I am using the latest version of flutter and the packages.

How can I fix this?

Thanks You!

Solution

I solved the problem using Hive.initFlutter(). Here’s the code:

import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';


void main() async {
  await Hive.initFlutter()
  runApp(MyApp());
}

Answered By – Pythony

Leave a Comment