试图转换旧代码为webview插件3到4,但坚持如何将消息传输回网页.
下面是在网页中触发receivePhoto()函数的函数,但不知何故没有触发(终端显示的是jsCode)。
void _pickfile() async {
final pickedFile = await ImagePicker().pickImage(source: ImageSource.camera);
if (pickedFile != null) {
final bytes = await pickedFile.readAsBytes();
final base64 = base64Encode(bytes);
final jsCode = "receivePhoto('$base64');";
await WebViewController().runJavaScript(jsCode);
print(jsCode);//this print works
} else {
// User canceled the picker
}
}
这是主代码:
class WebViewApp extends StatefulWidget {
const WebViewApp({Key? key}) : super(key: key);
@override
State<WebViewApp> createState() => _WebViewAppState();
}
class _WebViewAppState extends State<WebViewApp> {
WebViewController controller = WebViewController()
..enableZoom(false)
..setJavaScriptMode(JavaScriptMode.unrestricted)
..addJavaScriptChannel('FileInputChannel', onMessageReceived: (message) async {
if (message.message == 'pickFile') {
_pickfile();
}
})
..loadRequest(
Uri.parse("https://youtube.com"),
);
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: WebViewWidget(controller: controller),
),
);
}
}
1条答案
按热度按时间oxcyiej71#
好了,我自己得到了答案,并在这里分享。
问题是由于控制器在初始化阶段无法再次状态,所以,在初始化它之前只需创建示例(控制器)。*using _controller看起来更清晰