nicowernli
nicowernli

Reputation: 3348

How to access Android resource strings from Flutter Plugin

I'm building a plugin for Flutter and I want to access the Android app resource strings from the plugin.

I'm trying using:

@Override
    public void onMethodCall(MethodCall call, Result result) {
        switch (call.method) {
            case "example":
                String value = context.getString(R.string.name);
                result.success(value);
                break;
            default:
                result.notImplemented();
                break;
        }
    }

But R.string points to the plugin resources, not the app resources.

Regards

Upvotes: 1

Views: 2482

Answers (1)

nicowernli
nicowernli

Reputation: 3348

OK I found a solution. I got this function from the Auth0 Android repo

So basically to get app resources from a plugin they use this function

private static String getResourceFromContext(@NonNull Context context, String resName) {
        final int stringRes = context.getResources().getIdentifier(resName, "string", context.getPackageName());
        if (stringRes == 0) {
            throw new IllegalArgumentException(String.format("The 'R.string.%s' value it's not defined in your project's resources file.", resName));
        }
        return context.getString(stringRes);
    }

Upvotes: 5

Related Questions