PARAS GUPTA
PARAS GUPTA

Reputation: 302

How to download files in Flutter WebView?

I am working on Flutter webview apps using Flutter Webview.

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:url_launcher/url_launcher.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child : const WebView(
            initialUrl: 'https://google.com',
            javascriptMode: JavascriptMode.unrestricted,
          ),
        )
      )
    );
  }
}

I try to use launchURL plugin but that will open predefined url in external browser window.

if (url.contains('.pdf')) {
    launchURL(url);
  }

What I want is to download the file in-app webview.

Upvotes: 6

Views: 2827

Answers (1)

MαπμQμαπkγVπ.0
MαπμQμαπkγVπ.0

Reputation: 6737

There is actually an existing package that you could use. Check the flutter_downloader package:

A plugin for creating and managing download tasks. Supports iOS and Android.

This plugin is using WorkManager on Android and NSURLSessionDownloadTask on iOS to run download tasks in background.

Here is an example that you can try:

import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:flutter_downloader_example/home_page.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterDownloader.initialize(debug: true, ignoreSsl: true);

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  static const _title = 'flutter_downloader demo';

  @override
  Widget build(BuildContext context) {
    final platform = Theme.of(context).platform;

    return MaterialApp(
      title: _title,
      theme: ThemeData.light(),
      darkTheme: ThemeData.dark(),
      home: MyHomePage(
        title: _title,
        platform: platform,
      ),
    );
  }
}

Upvotes: -1

Related Questions