Greenlight
Greenlight

Reputation: 195

Have I to handle Random.secure() unsupported error in Flutter?

Is there some configuration/android version/phone model/etc. in which Random.secure() can throw an unsupported error for real?

https://api.dart.dev/stable/2.18.3/dart-math/Random/Random.secure.html says: "If the program cannot provide a cryptographically secure source of random numbers, it throws an UnsupportedError".

Upvotes: 0

Views: 505

Answers (1)

Tim Brückner
Tim Brückner

Reputation: 2099

If you want to be sure, you'll have to take a look inside the code, wich extends the abstract class Random.

I found the following unit test in the dart sources:

https://github.com/dart-lang/sdk/blob/main/tests/lib/math/random_secure_unsupported_test.dart

// Test that `Random.secure()` throws `UnsupportedError` each time it fails.

import "package:expect/expect.dart";
import 'dart:math';

main() {
  var result1 = getRandom();
  var result2 = getRandom();

  Expect.isNotNull(result1);
  Expect.isNotNull(result2); // This fired for http://dartbug.com/36206

  Expect.equals(result1 is Random, result2 is Random);
  Expect.equals(result1 is UnsupportedError, result2 is UnsupportedError);
}

dynamic getRandom() {
  try {
    return Random.secure();
  } catch (e) {
    return e;
  }
}

Calling Random.secure() two times in a row seems to cause an issue as described in http://dartbug.com/36206, but only for IE browser and Dart2JS.

Upvotes: 1

Related Questions