Skip to content

Instantly share code, notes, and snippets.

@rohankandwal
Created April 29, 2023 20:59
Show Gist options
  • Save rohankandwal/c7dd80627fdade779d1e6154657cecf1 to your computer and use it in GitHub Desktop.
Save rohankandwal/c7dd80627fdade779d1e6154657cecf1 to your computer and use it in GitHub Desktop.
File Upload using WebView on Android
/// Read details on https://theprogrammingway.com/flutter-file-upload-using-webview-on-android/
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late final WebViewController controller;
@override
void initState() {
controller = WebViewController();
controller.loadRequest(
Uri.parse("https://theprogrammingway.com/html-file-upload/"));
addFileSelectionListener();
super.initState();
}
void addFileSelectionListener() async {
if (Platform.isAndroid) {
final androidController = controller.platform as AndroidWebViewController;
await androidController.setOnShowFileSelector(_androidFilePicker);
}
}
@override
Widget build(BuildContext context) {
return WebViewWidget(controller: controller);
}
/// Function for file selection from gallery
Future<List<String>> _androidFilePicker(FileSelectorParams params) async {
final result = await FilePicker.platform.pickFiles();
if (result != null && result.files.single.path != null) {
final file = File(result.files.single.path!);
return [file.uri.toString()];
}
return [];
}
}
@rohankandwal
Copy link
Author

There is nothing special to be done for iOS. The only problem is special configuration required for android.

@rohankandwal
Copy link
Author

@Emanoel7S This looks like issue on filepicker, check if you have configured it properly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment