I have the function below, I want to access the context globally and I don't know if it's a good idea, I'm getting the context from the Application, I have TestAppliction in the test environment and I don't have access to the Application class, so I decided to add an optional context parameter to my function.

String getErrorMessage(DioError error, {BuildContext context}) {
  String rawMessage = _getAnalyzedMessage(error);
  GlobalKey navKey = Application.navKey;

  if (navKey != null && navKey.currentContext != null)
    context = Application.navKey.currentContext;

  if (context != null)
    return AppLocalizations.of(context).translate(rawMessage);
    return rawMessage;

Is this a good idea?


2 Answers 2


Do it the other way around. Pass the second argument always from outside - in both the tests and the real use case.

It doesn't have to be a second parameter of a static function though. You can promote it to an instance method and pass the context to constructor of such class, if that makes it easier to consume...


By adding separate logic for your test case you are making it less representative of the code you are trying to test.

If AppLocalizations.of(null) returned an identity translator, then you could remove the final if statement.


Not the answer you're looking for? Browse other questions tagged or ask your own question.