如何在Flutter插件中访问Android应用的资源字符串
解决Flutter插件访问Android宿主应用资源字符串的问题
你遇到的这个问题很典型——默认情况下,插件里的R.string会直接指向插件自身模块的资源文件,而非宿主Android应用的。要访问宿主的资源,我们需要绕开插件自带的R类,直接从宿主的资源包中动态获取。
这里有两种可靠的实现方案:
方法一:用Resources.getIdentifier()动态查找资源
这种方法不需要提前知晓宿主资源的类,通过资源名称和类型就能定位到目标字符串,灵活性很高:
@Override public void onMethodCall(MethodCall call, Result result) { switch (call.method) { case "getHostString": // 接收Flutter端传入的宿主资源名称 String resName = call.argument("resName"); if (resName == null) { result.error("INVALID_ARG", "Resource name cannot be null", null); return; } // 获取宿主应用的Resources对象 Resources hostRes = context.getResources(); // 动态获取资源ID:参数依次为资源名、资源类型(这里是string)、宿主包名 int resId = hostRes.getIdentifier(resName, "string", context.getPackageName()); if (resId == 0) { result.error("NOT_FOUND", "Target string not exists in host app", null); return; } String targetString = hostRes.getString(resId); result.success(targetString); break; default: result.notImplemented(); break; } }
Flutter端调用示例(假设宿主有R.string.app_name资源):
Future<String?> fetchHostAppName() async { try { return await _channel.invokeMethod('getHostString', {'resName': 'app_name'}); } on PlatformException catch (e) { print("Error: ${e.message}"); return null; } }
方法二:通过PackageManager获取宿主资源包
如果需要更严谨地访问宿主资源,可以通过PackageManager获取宿主的完整资源信息:
@Override public void onMethodCall(MethodCall call, Result result) { switch (call.method) { case "getHostAppResource": String resName = call.argument("resName"); if (resName == null) { result.error("INVALID_ARG", "Resource name is required", null); return; } try { // 获取宿主应用的PackageInfo PackageInfo packageInfo = context.getPackageManager().getPackageInfo( context.getPackageName(), PackageManager.GET_RESOURCES ); // 直接获取宿主的Resources实例 Resources hostRes = context.getPackageManager().getResourcesForApplication(packageInfo.applicationInfo); int resId = hostRes.getIdentifier(resName, "string", context.getPackageName()); if (resId == 0) { result.error("NOT_FOUND", "Resource not found in host", null); return; } result.success(hostRes.getString(resId)); } catch (PackageManager.NameNotFoundException e) { result.error("EXCEPTION", "Failed to access host resources", e.getMessage()); } break; default: result.notImplemented(); break; } }
重要注意事项
- Flutter端传入的资源名称必须完全匹配宿主
strings.xml中对应的name属性值,区分大小写 - 宿主应用的多语言资源会被自动识别,
getResources()会返回当前系统语言对应的字符串 - 绝对不要尝试直接引用宿主的
R类,插件编译阶段无法访问宿主的类文件,会直接导致编译失败
内容的提问来源于stack exchange,提问作者nicowernli
相关产品推荐
相关产品推荐

