How to share image downloaded from flutter - android

I use flutter to save a widget as an image in flutter. I have no problem with downloading the image but im having troubke with sharing the image. Is there a way i way share the downlaoded image without leaving the application?
Here's my present code
onPressed: () async {
if (await Permission.storage.request().isGranted) {
screenshotController.capture(pixelRatio: 1.5);
screenshotController.capture().then((File image) async {
await ImageGallerySaver.saveImage(image.readAsBytesSync());
Navigator.of(context, rootNavigator: true).pop();
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text("Image Saved to Gallery"),
duration: const Duration(seconds: 1),
),
);
}).catchError((onError) {
// print(onError);
});
} else {
await Permission.storage.request();
}
}

You need to handle the image as any other file.
If you do not intend to use a server between the two users, its a bit tricky because one of them must act as one, but if you will use a server, i suggest you to follow this post:
https://dev.to/carminezacc/advanced-flutter-networking-part-1-uploading-a-file-to-a-rest-api-from-flutter-using-a-multi-part-form-data-post-request-2ekm
It's pretty recent and will help you with the app code and even with a server sample writen in nodejs. The next parts of the post teach you to do what you want.

Related

expo-camera takePictureAsync() not working on Android

I recently updated several lines of code in a managed expo project, unrelated to the camera functionality. It still works fine on iOS, only Android does not work. I had released a previous version one month ago that worked well. When I revert back to the old commit from then, though, it also does not work on Android (iOS fine).
expo 44.0.6
expo-camera 12.1.2
react 17.0.1
react-native 0.64.3
There is no issue launching the camera, etc. Rather, the issue occurs at takePictureAsync, which hangs and then does not return anything.
const snapPic = async () => {
const { status } = await Camera.getCameraPermissionsAsync();
if (status != 'granted') {
alert('Please grant access to camera and retry.');
await Camera.requestCameraPermissionsAsync();
return;
}
const options = { quality: 0.1 };
const photo = await this.camera.takePictureAsync(options);
this.camera.pausePreview();
this.setState({imageSource: photo.uri});
};
<Camera style={styles.cameraBox} ref={ref => {this.camera = ref}} />
Please let me know what other information I can provide, if necessary. Thanks in advance!
Instead of pause preview method. Try it with skipProcessing to false inside option object

Flutter - How to know if user shared my app or not?

I have implemented the below given code to let user share my app. It works fine, but how can I know if the user actually shared my app or not? Because my app unlocks a certain feature if the user shares the app.
[Package used:- share_plus 3.0.4 ]
onTap: () async {
const _textShareUrl =
'https://www.youtube.com/watch?v=CNUBhb_cM6E&list=PLk6qkmrzOcdx5R4-UqI_jDPYsLWNnZ1dq&index=2';
await Share.share(
'Social share test\n\n$_textShareUrl');
Future.delayed(const Duration(seconds: 10), () {
setState(() => _share = true);
});
},
There is already an open issue:
https://github.com/fluttercommunity/plus_plugins/issues/386

Cancelling/Exiting Photo Library in Android using react-native-image-crop-picker

In my React Native app, I use the react-native-image-crop-picker package to have access to user's photo library.
It works nicely but if the user has no images in his/her photo library, I want to give the user a way to cancel out or exit it. How do I do that? Currently in Android, I click the element e.g. button or menu item to access user's photo library but then I get stuck there -- see image below:
And if I use gestures to get back to my app, I get the following warning.
Possible Unhandled Promise Rejection
My code is pretty basic at this point. When the user presses a button, I call this function which invokes the image picker:
pickImage() {
ImagePicker.openPicker({
width: 400,
height: 250,
cropping: true
}).then(image => {
onFilePicked(image);
});
}
Basically, I just need to give the user a way to cancel out of picking an image from the photo gallery. I'd appreciate some pointers on this. Thanks!
The npm package react-native-image-crop-picker is the most used library in react-native to choose Images and videos across the platforms.
It opens a default native Intent from which we can select media files from the gallery, We are not able to customize the view of it as its pure native intent is available into the native device.
And the error message Possible Unhandled Promise Rejection We get is the default error from the library, when the user goes back into our app without selecting a single image or video.
To handle the error message we have to wrap our code inside to try and catch it.
For Ex:
ImagePicker.openPicker({
width: 400,
height: 250,
cropping: true
}).then(image => {
onFilePicked(image);
}).catch(err => {
console.log('Error : ', err.message)
});
// - OR -
try {
const imagePickerRes = await ImagePicker.openPicker({
width: 400,
height: 250,
cropping: true
})
console.log('imagePicker Result : ', imagePickerRes)
} catch (err) {
console.log('Error : ', err.message)
}

How can I keep background tasks alive in background on Android using Flutter?

I have a bussness app that count time, set macros and show notification and alerts.
I have a problem when app goes to background and Android stop my counting tasks.
I tried many things to keep these tasks alive, but I failed. This notification need to work offline, so FCM not a good solution.
How can I work arround it?
Obs.: When app goes to foreground, all tasks work and show all notifications... But I need to alert user just in time, not only in foreground.
I founded a solution!
Searching the site https://dontkillmyapp.com/ I saw many apps with the same problem and some solution ideas for differets brands and models.
After checking some of them, I saw that many installed apps has this config for default, so I search how can I do it programactlly.
Here the solution:
pubspec.yaml
android_power_manager: ^0.1.6
permission_handler: ^5.0.1+1
Function:
void init() async {
var status = await Permission.ignoreBatteryOptimizations.status;
print("status: $status");
if (status.isGranted) {
print(
"isIgnoring: ${(await AndroidPowerManager.isIgnoringBatteryOptimizations)}");
if (!(await AndroidPowerManager.isIgnoringBatteryOptimizations)) {
AndroidPowerManager.requestIgnoreBatteryOptimizations();
}
} else {
Map<Permission, PermissionStatus> statuses = await [
Permission.ignoreBatteryOptimizations,
].request();
print(
"permission value: ${statuses[Permission.ignoreBatteryOptimizations]}");
if (statuses[Permission.ignoreBatteryOptimizations].isGranted) {
AndroidPowerManager.requestIgnoreBatteryOptimizations();
} else {
exit(0);
}
}
}
AppWidget.dart (main)
#override
Widget build(BuildContext context) {
init();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
DataTransferService().initTimerTask();
return MaterialApp(
navigatorKey: Modular.navigatorKey,
title: APP_NAME,
theme: ThemeData(
primarySwatch: Colors.green,
),
initialRoute: '/',
routes: {
'/': (context) => LoginPage(),
'/home': (context) => HomePage(),
'/notification': (context) => NotificationPage(),
'/alerts': (context) => AlertsPage(),
},
onGenerateRoute: Modular.generateRoute,
);
}
So, the app ask permission (if needed) and, if permission is granted, ask user to set app to ignore battery optimization.
Now the notifications are working all rigt! =]
You probably want an Android service to run these tasks (foreground or background depending on your specific requirements).
It looks like there are some Flutter packages that have already been built to help with this, but I'd pay close attention to what they offer in terms of support for different Android versions.

SharedPreferences working on android emulator but not on real device

As said in the title, I have some bools and Strings stored in SharedPreferences. It work like a charm with the emulator and when i install my app on my real device, the bool and Strings are just not sotred. I'm using api 29 on the emulator and 30 on my device, can it be this? (I just checked and when debugging on my real phone it worked!! But still not when i'm installing the app with the apk file from the build task...)
Any ideas? I don't think my code will be very relevant here but if needeed I can add it!
Thanks for your help!
Also, the app is much heavier when debugging (almost 5 times) and much less smooth, any ideas why? maybe because of the SharedPrefs?
Edit of the code:
Switch(
value: appsLoad.instagram ?? false,
onChanged: (value) {
setState(() {
appsLoad.instagram = value;
sharedPref.save("user", appsLoad);
});
},
),
This is how i save the value, the sharePref.save refers to
save(String key, value) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString(key, json.encode(value) ?? false);
}
i used a lot of this website for the sharedPreferences.
If you read the setState comment section
Generally it is recommended that the setState method only be
used to wrap the actual changes to the state, not any computation
that might be associated with the change. For example, here a
value used by the [build] function is incremented, and then the
change is written to disk, but only the increment is wrapped in
the setState:
Future<void> _incrementCounter() async {
setState(() {
_counter++;
});
Directory directory = await getApplicationDocumentsDirectory();
final String dirName = directory.path;
await File('$dir/counter.txt').writeAsString('$_counter');
}
Following the example you shouldn't call the future inside setState
Switch(
value: appsLoad.instagram ?? false,
onChanged: (value) async {
setState(() {
appsLoad.instagram = value;
});
await sharedPref.save("user", appsLoad);
},
),
Take note an emulator doesn't run as fast as a device (with the profile/debug mode its slower than a real one) so that's why in an emulator you cannot perceive this kind of error

Categories

Resources