Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Upload does not work inside Webview, Flutter

I have a website and I converted that website into flutter android application using webview_flutter plugin, everything is working fine.

But there is an issue, there is a form on website in which there is a file input in the form. On website everything works fine but when I click on upload file from android application which I created using webview_flutter plugin, the file input dose not works.

When I click on upload file, it dose not open any popup or anything to allow me to select file from my phone and to upload into the form.

This is my main.dart code:

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:custom_splash/custom_splash.dart';
import 'package:connectivity/connectivity.dart';
import 'package:selfcare/nointernet.dart';

void main() {

  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());

}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: "Self Care",
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: Colors.red,
        ),
        home: Scaffold(body: splash()));
  }
}

class splash extends StatefulWidget {
  @override
  _splashState createState() => _splashState();
}

class _splashState extends State<splash> {
  String result = '';
  var Colorsval = Colors.white;

  @override
  void initState() {
    CheckStatus();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (result != null && result == "Connected") {
      return CustomSplash(
        //backGroundColor: Color(0xFFFF9800),
        imagePath: "assets/images/logo.png",

        home: WebViewClass(),
        duration: 10,
        animationEffect: "zoom-in",
      );
    } else if (result != null && result == "NoInternet") {
      return CustomSplash(
        //backGroundColor: Color(0xFFFF9800),
        imagePath: "assets/images/logo.png",

        home: NoInternetPage(),
        duration: 10,
        animationEffect: "zoom-in",
      );
    } else if (result == null) {
      return CustomSplash(
        //backGroundColor: Color(0xFFFF9800),
        imagePath: "assets/images/logo.png",

        home: NoInternetPage(),
        duration: 10,
        animationEffect: "zoom-in",
      );
    } else {
      return CustomSplash(
        //backGroundColor: Color(0xFFFF9800),
        imagePath: "assets/images/logo.png",

        home: NoInternetPage(),
        duration: 10,
        animationEffect: "zoom-in",
      );
    }
  }

  void CheckStatus() {
    Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      if (result == ConnectivityResult.mobile ||
          result == ConnectivityResult.wifi) {
        ChangeValues("Connected", Colors.green[900]);
      } else {
        ChangeValues("NoInternet", Colors.red[900]);
      }
    });
  }

  void ChangeValues(String resultval, Color colorval) {
    setState(() {
      result = resultval;
      Colorsval = colorval;
    });
  }
}

class WebViewClass extends StatefulWidget {
  WebViewState createState() => WebViewState();
}

class WebViewState extends State<WebViewClass> {
  num position = 1;

  final key = UniqueKey();

  doneLoading(String A) {
    setState(() {
      position = 0;
    });
  }

  startLoading(String A) {
    setState(() {
      position = 1;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Permission.mediaLibrary.request();
    Permission.phone.request();
    Permission.photos.request();
    Permission.storage.request();
    Permission.camera.request();
  }
  //Check Internet Code Starts

  //Check Internet Code Ended here
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        //appBar: AppBar(title: Text('Show ProgressBar While Loading Webview')),
        appBar: PreferredSize(
          child: Container(),
          preferredSize: Size.fromHeight(0.0),
        ),
        body: IndexedStack(index: position, children: <Widget>[
          WebView(
            initialUrl: 'http://mywebsite.com',
            javascriptMode: JavascriptMode.unrestricted,
            key: key,
            onPageFinished: doneLoading,
            onPageStarted: startLoading,
            //onWebResourceError: ,
          ),
          Container(
            color: Colors.white,
            child: Center(
                child: CircularProgressIndicator(
              valueColor: new AlwaysStoppedAnimation<Color>(Colors.red),
            )),
          ),
        ]));
  }
}

And this is the flutter webview plugin I used:

dependencies:
  webview_flutter: ^1.0.7

I also used some permissions to get rid of this problem but not solved it, the permissions:

Permission.mediaLibrary.request();
Permission.phone.request();
Permission.photos.request();
Permission.storage.request();
Permission.camera.request();
like image 879
Muhammad Noman Avatar asked Mar 31 '26 19:03

Muhammad Noman


1 Answers

  1. import these two library by webview_flutter latest package
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
  1. import file_picker latest package
  2. now add this function
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 [];
}
  1. now add this function and call it in initial state
void addFileSelectionListener() async {
    if (Platform.isAndroid) {
      final androidController =
          widget.controller.platform as AndroidWebViewController;
      await androidController.setOnShowFileSelector(_androidFilePicker);
    } 
}

now it will work well

like image 83
HANAN ASHRAF Avatar answered Apr 03 '26 10:04

HANAN ASHRAF