Read PEM file from assets in flutter - Null check operator used on a null value

Viewed 354

main.dart:

main(List<String> args) async {
  String testTextFile = await rootBundle.loadString('assets/privatekey.pem');
  // rootBundle.load() returns the same error
}

File system:

enter image description here

pubspec.yaml:

flutter:
  uses-material-design: true

  assets:
    - assets/test.txt
    - assets/privatekey.pem
    - assets/publickey.pem

Loading either the private, public or test textfile with the above code returns _CastError (Null check operator used on a null value). I have tried:

  • flutter clean
  • recreating the project
  • creating other asset folders
  • trying a txt instead of a pem

Here is my flutter doctor output:

flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.2.1, on Linux, locale en_ZA.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[✗] Chrome - develop for the web (Cannot find Chrome executable at google-chrome)
    ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.
[✓] Android Studio (version 4.2)
[✓] Connected device (1 available)

! Doctor found issues in 1 category.
1 Answers

If your trying to do this in main before runApp, you need to make sure that the flutter engine is initialised properly. try adding WidgetsFlutterBinding.ensureInitialized() on the first line:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  String testTextFile = await rootBundle.loadString('assets/privatekey.pem');
  runApp(MyApp());
}
Related