0

I'm using flutter_localizations.dart package to Localize my App in different Languages. Usually, I use S.of(context).wordToLocalize to call the String according to each language.

However, in the login process, I have no context, so I cannot use the same procedure. I I have the following error:

Undefined name 'context'. Try correcting the name to one that is defined, or defining the name.

The code where I need to use it, is as follows

import 'dart:async';
import 'package:aplians_fish/generated/l10n.dart';

    
class Validators {

final validarEmail = StreamTransformer<String, String>.fromHandlers(
  handleData: (email, sink) {

    Pattern pattern = r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
    RegExp regExp = new RegExp(pattern);
    if (regExp.hasMatch(email)) {
      sink.add(email);
    } else {
      sink.addError('It must be a valid e-mail'); 

// I would like to change the previous line for S.of(context).validEmail

    }
  }
);

How can I call Flutter Localization in this code?

David L
  • 1,134
  • 7
  • 35
  • Did you try this solutions ? https://stackoverflow.com/questions/61563074/flutter-localization-without-context – Xsims May 12 '21 at 21:49
  • 1
    Yes, I saw it. However, I am using a package to auto-generate l10n.dart so I am not comfortable with manual changes on this side. – David L May 12 '21 at 21:57
  • Try use get_it https://stackoverflow.com/a/68390265/699604 – zap Jul 15 '21 at 08:19
  • This is my solution: https://stackoverflow.com/a/69037938/1034225 – mabg Sep 02 '21 at 23:21

1 Answers1

0

You can initialize Validators with a BuildContext for the Localization.

class Validators {
  Validators({required BuildContext context}) 
      :  _context = context;

  final BuildContext _context;

  // You can now call BuildContext inside Validators like
  // AppLocalizations.of(_context).validEmail
}

The class can be initialized in Widget build() where BuildContext can be passed.

@override
Widget build(BuildContext buildContext) {
  Validators(context: buildContext);
  return Scaffold(...);
}
Omatt
  • 8,564
  • 2
  • 42
  • 144