33. Flutter Tutorial for Beginners – Download Image from URL to Gallery

0
671

To do that you have to use few packages such as Dio, Permission Handler and image_gallery_saver.

Step 1. Go to the following links:

https://pub.dev/packages/image_gallery_saver#-example-tab-

https://pub.dev/packages/dio#-installing-tab-

https://pub.dev/packages/permission_handler#-installing-tab-

Step 2. Open your flutter project, then open pubspec.yml file

Step 3. Add dio, permission handler and image_gallery_saver dependencies to your package’s pubspec.yaml file

For example:

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  permission_handler: ^4.2.0+hotfix.3
  image_gallery_saver: ^1.2.2
  dio: ^3.0.9

Step 4. Then click “Packages get”

Step 5. Import those packages into your dart file.

import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:dio/dio.dart';
import 'dart:typed_data';
import 'package:permission_handler/permission_handler.dart';

Step 6. Open android AndroidManifest.xml file from PROJECT_ROOT/android/app/src/main/ AndroidManifest.xml. And add the following code before <application> tag to get storage permission.

For iOS, open Info.plist file from PROJECT_ROOT/ios/Runner/Info.plist and add the following code to get permission.

NSPhotoLibraryAddUsageDescription
Need permission for storing Image

Step 7. Use the following code to save image into gallery.

@override
void initState() {
  // TODO: implement initState
  super.initState();
  PermissionHandler().requestPermissions([
    PermissionGroup.storage,
  ]);
}

_save() async {
  var response = await Dio().get("http://34.71.214.132/wp-content/uploads/2019/06/logo-300x52.png", options: Options(responseType: ResponseType.bytes));
  final result = await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
  print(result);
}

You can use this _save function into any button. When the button on pressed then download the image into gallery.

Full example:

import 'package:flutter/material.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:dio/dio.dart';
import 'package:permission_handler/permission_handler.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    PermissionHandler().requestPermissions([
      PermissionGroup.storage,
    ]);
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Container(
          child: RaisedButton(
            child: Text('Save Image'),
            onPressed: ()
            {
              _save();
            },
          ),
        ),
      ),
    );
  }

  _save() async {
    var response = await Dio().get("http://34.71.214.132/wp-content/uploads/2019/06/logo-300x52.png", options: Options(responseType: ResponseType.bytes));
    final result = await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
    print(result);
  }
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pisofts.flutter_tutorial">
    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="flutter_tutorial"
        android:icon="@mipmap/launcher_icon">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

Info.plist File:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>NSPhotoLibraryAddUsageDescription</key>
    <string>Need permission for storing Image</string>
    <key>io.flutter.embedded_views_preview</key>
    <string>YES</string>
   <key>CFBundleDevelopmentRegion</key>
   <string>$(DEVELOPMENT_LANGUAGE)</string>
   <key>CFBundleExecutable</key>
   <string>$(EXECUTABLE_NAME)</string>
   <key>CFBundleIdentifier</key>
   <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
   <key>CFBundleInfoDictionaryVersion</key>
   <string>6.0</string>
   <key>CFBundleName</key>
   <string>flutter_tutorial</string>
   <key>CFBundlePackageType</key>
   <string>APPL</string>
   <key>CFBundleShortVersionString</key>
   <string>$(FLUTTER_BUILD_NAME)</string>
   <key>CFBundleSignature</key>
   <string>????</string>
   <key>CFBundleVersion</key>
   <string>$(FLUTTER_BUILD_NUMBER)</string>
   <key>LSRequiresIPhoneOS</key>
   <true/>
   <key>UILaunchStoryboardName</key>
   <string>LaunchScreen</string>
   <key>UIMainStoryboardFile</key>
   <string>Main</string>
   <key>UISupportedInterfaceOrientations</key>
   <array>
      <string>UIInterfaceOrientationPortrait</string>
      <string>UIInterfaceOrientationLandscapeLeft</string>
      <string>UIInterfaceOrientationLandscapeRight</string>
   </array>
   <key>UISupportedInterfaceOrientations~ipad</key>
   <array>
      <string>UIInterfaceOrientationPortrait</string>
      <string>UIInterfaceOrientationPortraitUpsideDown</string>
      <string>UIInterfaceOrientationLandscapeLeft</string>
      <string>UIInterfaceOrientationLandscapeRight</string>
   </array>
   <key>UIViewControllerBasedStatusBarAppearance</key>
   <false/>
   <key>UIStatusBarHidden</key>
   <true/>

</dict>
</plist>

LEAVE A REPLY

Please enter your comment!
Please enter your name here