-1
\$\begingroup\$

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);
  else
    return rawMessage;
}

Is this a good idea?

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

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...

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$

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