Why is riverpod failing even to initialize in project? Method not found: ‘Error.throwWithStackTrace’

Error.throwWithStackTrace was added in Dart 2.16 (Flutter version 2.10 from Feb 8, 2022).

https://api.flutter.dev/flutter/dart-core/Error/throwWithStackTrace.html

(Check the @Since annotation.)

If your Flutter/Dart version is below that, you’ll get the error you saw.

Two options that may help are:

  1. Specify an exact version of dependencies (don’t use ^ ahead of version)
  2. upgrade Flutter/Dart to at least 2.10/2.16
flutter upgrade

If your problematic package (hooks_riverpod: ^2.0.0 in your case) is listed with ^, it’ll use the latest version that doesn’t break dependencies.

I’m guessing that when you created a new project and used that same dependency version, upon initial pub get it downloaded a newer version of the package (or a newer version of a dependency that that package uses) into “pub cache” which is relying on the new Error API method.

Your project will store this information in:

<your_project_dir>/dart_tool/package_config.json

The min Dart SDK version listed for the package should normally have changed from 2.12 to 2.16. (update: it’s been updated now) This would give us a hint that we need to update our Flutter/Dart if we see our build failing.

In an earlier version of this answer, I noted that the ^ prefix on package dependency versions is supposed to prevent these types of issues, but I’m no longer certain it was meant to cover this situation where the underlying platform needs to be updated (as opposed to a breaking change in the API of the package itself).

Anyways, at first glance, it might make sense to go from 2.0.0 to 3.0.0 for a package version # when it depends on a new core Dart API method that did not exist when 2.0.0 was published.

Notes

The author of riverpod also wrote the new API for Error.throwWithStackTrace so likely the latest version of hooks_riverpod is using the latest API changes. (The version you’re listing 2.0.0 is pre-release currently). You could try earlier versions of riverpod in your pubspec.yaml (such as 1.0.3)

Leave a Comment