Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set image as wallpaper in flutter?

Tags:

flutter

dart

I'm confusing in how to set an image as wallpaper in flutter, I have tried to use this code below reference from here!

my flutter code: in this code, I tried to make file from URL

//get URL image and save it and create a file
    _setWallp(String imageUrl) async {


        try {
          var httpClient = http.Client();
       var list = await httpClient.readBytes(imageUrl);


          final tempDir = await getTemporaryDirectory();
          final file = await new Io.File('${tempDir.path}/image.jpg').create();
          file.writeAsBytes(list);

          final channel = const MethodChannel('setwallpaper');
          channel.invokeMethod('shareFile', 'image.jpg');
        } catch (e) {
          print('Share Error :$e');
        }
      }

my java code : in this java code, I tried to set bitmap as wallpaper from file path that I created in flutter

//call method channel from flutter
        private static final String SHARE_CHANNEL = "setwallpaper";

      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GeneratedPluginRegistrant.registerWith(this);

        new MethodChannel(this.getFlutterView(), SHARE_CHANNEL).setMethodCallHandler(new MethodChannel.MethodCallHandler() {
          public final void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
            if (methodCall.method.equals("shareFile")) {
              shareFile((String) methodCall.arguments);
            }
          }
        });
      }


          private void shareFile(String path) {
            File imgFile = new  File(this.getApplicationContext().getCacheDir(), path);


        // set bitmap to wallpaper
            Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
            WallpaperManager wm = WallpaperManager.getInstance(this);
            try{
              wm.setBitmap(bitmap);
            }catch (IOException e){
              Log.e(TAG, "shareFile: cannot set image as wallpaper",e );
            }
          }
        }

debug console message:

//message from console
    E/flutter (10376): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
    E/flutter (10376): PlatformException(error, Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference, null)
    E/flutter (10376): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:547:7)
    E/flutter (10376): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:279:18)
    E/flutter (10376): <asynchronous suspension>
    E/flutter (10376): #2      FullScreenState._setWallp (file:///D:/fltr/cat_wallpapers/lib/fullscreen.dart:111:15)
    E/flutter (10376): <asynchronous suspension>
    E/flutter (10376): #3      FullScreenState.build.<anonymous closure> (file:///D:/fltr/cat_wallpapers/lib/fullscreen.dart:71:31)
    E/flutter (10376): #4      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:494:14)
    E/flutter (10376): #5      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:549:30)
    E/flutter (10376): #6      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
    E/flutter (10376): #7      TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:161:9)
    E/flutter (10376): #8      TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:94:7)
    E/flutter (10376): #9      PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:315:9)
    E/flutter (10376): #10     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
    E/flutter (10376): #11     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
    E/flutter (10376): #12     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:143:19)
    E/flutter (10376): #13     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:121:22)
    E/flutter (10376): #14     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:101:7)
    E/flutter (10376): #15     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:64:7)
    E/flutter (10376): #16     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:48:7)
    E/flutter (10376): #17     _invoke1 (dart:ui/hooks.dart:134:13)
    E/flutter (10376): #18     _dispatchPointerDataPacket (dart:ui/hooks.dart:91:5)
    D/EGL_emulation(10376): eglMakeCurrent: 0xb429e760: ver 2 0
    I/FlutterActivityDelegate(10376): onResume setting current activity to this
    D/EGL_emulation(10376): eglCreateContext: 0xb429e820: maj 2 min 0 rcv 2
    D/EGL_emulation(10376): eglMakeCurrent: 0xb429e820: ver 2 0
    D/EGL_emulation(10376): eglMakeCurrent: 0xb429e760: ver 2 0
    D/EGL_emulation(10376): eglMakeCurrent: 0xb429e820: ver 2 0
    I/flutter (10376): Another exception was thrown: type 'Future<dynamic>' is not a subtype of type 'Future<File>' //didn't understand about this

need help.. thank you

like image 952
Dimas N AL Avatar asked Nov 08 '22 06:11

Dimas N AL


1 Answers

Using Dio library...Make Sure That First You Download The Image And Once Downloaded Set As Wallpaper

Future<Null> setWallpaper() async {
Dio dio = Dio();
try {
  var dir = await getTemporaryDirectory();

  await dio.download(widget.img, "${dir.path}/myimage.jpeg",
      onProgress: (rec, total) {
    setState(() {
      downloading = true;
      progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
      print(progressString);
      if (progressString == "100%") {
        _setWallpaer();
      }
    });
  });
} catch (e) {}

setState(() {
  downloading = false;
  progressString = "Completed";
});}

Future<Null> _setWallpaer() async {
String setWallpaper;
try {
  final int result =
      await platform.invokeMethod('setWallpaper', 'myimage.jpeg');
  setWallpaper = 'Wallpaer Updated....';
} on PlatformException catch (e) {
  setWallpaper = "Failed to Set Wallpaer: '${e.message}'.";
}
setState(() {
  _setWallpaper = setWallpaper;
});}

You Can See Full Source Code If It Can Help.....

https://github.com/pratiktimer/flutterwallpaper

like image 72
Pratik Banawalkar Avatar answered Nov 30 '22 03:11

Pratik Banawalkar