By Qiaqia Li
When I developed Learning Card App for Android, I met a problem that the picture I saved didn't appear in the album, I had to find it in the file system, that's very inconvenient., so I tried to fix this. I looked up dart package to find out this function, unfortunately there was no solution. I had to writing custom platform-specific code to refresh album. The following is the specific code.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
...
class _MyHomePageState extends State<MyHomePage> {
static const platform = const MethodChannel('samples.liqiaqia.com/refreshAlbum');
// Refresh album through platform channel.
Future<void> _refreshAlbum(String filePath) async {
try {
await platform.invokeMethod('refreshAlbum',<String, dynamic>{
'filePath': filePath,
});
} on PlatformException catch (e) {
//handle error
}
}
Future _saveImage() async {
filePath = '...';
//Save image...
//Calling refresh album function
_refreshAlbum(filePath);
}
}
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import java.io.File;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "samples.liqiaqia.com/refreshAblum";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodCallHandler() {
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("refreshAlbum")) {
refreshAlbum(methodCall.argument("filePath"));
}
}
}
);
}
private void refreshAlbum(String filePath) {
Uri uri = Uri.fromFile(new File(filePath));
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
sendBroadcast(intent);
}
}
Finally, the picture appears in your album after you saving the picture.