Flutter - How to save a file requesting permission with Permission Handler if my code is deprecated? - flutter

I'm new to Flutter and I've been following this tutorial but it's from 2020 and I know a lot of things have changed.
I want to save a file on my local phone and apparently I need to ask permission to do so. I'm not sure if checking the platform is still needed or not.
I don't want to run the --no-sound-null-safety command.
This is the only part that I wasn't able to update by myself.
_save() async {
if (Platform.isAndroid) {
await _askPermission();
}
var response = await Dio().get(widget.imgUrl!,
options: Options(responseType: ResponseType.bytes));
final result =
await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
print(result);
Navigator.pop(context);
}
_askPermission() async {
if (Platform.isIOS) {
await PermissionHandler().requestPermissions([PermissionGroup.photos]);
} else {
await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
}
}
The _save method seems alright but I wonder if there's something to update there as well.
The _askPermission method is the one that I need help with.

Related

Firebase remote config not updating and using older value+ Flutter

When we have a higher version available on the play store. This feature redirects users to the app store to install updates. But it is not working on a few devices. The user still using the older version. If the user clears the storage then an alert is displayed. We can not ask our users to clear storage. Any help would be greatly appreciated.
#override
void initState() {
super.initState();
try {
versionCheck(context);
} catch (e) {
print(e);
}
}
versionCheck(context) async {
//Get Current installed version of app
final PackageInfo info = await PackageInfo.fromPlatform();
double currentVersion =
double.parse(info.version.trim().replaceAll(".", ""));
//Get Latest version info from firebase config
final FirebaseRemoteConfig remoteConfig =
await FirebaseRemoteConfig.instance;
try {
// Using default duration to force fetching from remote server.
await remoteConfig.fetch();
await remoteConfig.fetchAndActivate();
remoteConfig.getString('force_update_current_version');
double newVersion = double.parse(remoteConfig
.getString('force_update_current_version')
.trim()
.replaceAll(".", ""));
if (newVersion > currentVersion) {
_showVersionDialog(context);
}
} on Exception catch (exception) {
// Fetch throttled.
print(exception);
} catch (exception) {
print('Unable to fetch remote config. Cached or default values will be '
'used');
}
}
When I tried to print the values I am getting the same values new:160.0 current:160.0, clearing the storage of the app from the setting displays the alert.
I think your code in general looks right to me. Though there is a redundant line:
remoteConfig.getString('force_update_current_version');
But this should be fine.
What I am concerned about is that you replace all your . with empty and convert the version to a number. This can result in a bug if there are two versions like:
1.21.4 vs 1.2.15. The first one is supposed to be newer, but the code will get 1214 > 1215 is false

How to handle reading from database when API-request hasn't finished yet to save to database in Flutter?

For my App i'm loading the link for the background-image for each screen from my API.
Right after the query that downloads and saves the image-link, i'm querying the link from the database.
The problem now is, that the function isn't waiting for the download and saving to finish although i'm using await, therefor i get an empty result from the database and get an error from the imageloader.
Future<String> downloadAsset(String name) async {
final Map<String, String> _json = {
'mandant': Config.mandant,
'name': name
};
final query = MakePost('get_app_assets', false, _json, saveAsset);
await query.queryAPI(); // Function won't wait for this to finish
String ret = await dbAppAssets.getText(name); // Get link from database
return ret;
}
I've already tried to use .then(), but the same thing happens.
This only happens initially on the first call of each screen, but how is this normally beeing handled?
I'm using riverpod with futureProviders if that matters.
I do not know where you are using the downloadAsset function, but when you use Future on a function you should also await the function where you are using it, for example:
Future<void> _reverseScrollToTopAnimation() async {
await controller!.reverse();
_showBackToTopButton = false; // hide the back-to-top button
}
then, wherever you call it you should also await that function:
await _reverseScrollToTopAnimation();
If not the function will act as a synchronous operation even though you are using await inside the function.

Flutter: issue with Future which block a function

I am currently developping a flutter application with Dart. I want to add some local notification when there is something new.
For that I'm using a periodic task with workmanager, which make a http request to check the last "news". The issue here is that the function stop at client.get()
Future<List<String>> _grepLastNews() async {
var client2 = new http.Client();
debugPrint("here");
//issue below
final response =
await client2.get('http://..../lireLastNews.php').timeout(Duration(seconds: 4));
client2.close();
debugPrint("here 2");
var body;
if (response.statusCode == 200) {
body = jsonDecode(response.body);
} else {
return ["0","0"];
}
return jsonDecode(body);
}
Here you can find the output:
output
You can see it stop before the second checkpoint... I have tried with and without timeout, with changing the name of the other http client of the application but nothing work. I must add that I have an other http client which work perfectly ( but not in background ^^).
Thanks for helping me
EDIT: I tried with
await Future.delayed(Duration(seconds: 2),() => ["0","0"]);
but the output is the same so the issue is not with http.get but about the future which I don't know why stop there.
EDIT 2: In fact in an async function I tried
debugPrint("here 2");
await Future.delayed(Duration(seconds: 2));
debugPrint("here 3");
and it never go for "here 3".
EDIT 3:
I tried differents variant using Future.wait([_grepLastNews()]); but it don't work: it continue until raising an error because of the null result of _grepLastNews().

permission denied to access media from storage in multi image picker

i am uploading images from gallery to app, my app ask for permission automatically but dont know what happen now it is not asking for the permission and getting error "permission denied " when i try to open gallery in the app
loadGallery() async {
List<Asset> resultImages = List<Asset>();
try {
resultImages = await MultiImagePicker.pickImages(
maxImages: 10,
selectedAssets: images,
);
} catch (e) {
print("error is : $e");
}
setState(() {
images = resultImages;
});
}
In your AndroidManifest.xml file located in android/app/src/main, include these lines,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
under the "<manifest.." tag.
There can be many scenarios that can be in the picture.
1) Maybe you have clicked on the permission for never option, where it does not asks permission later.
you have to check if you have the permission for accessing I have written the code check it just wrote an example, modify accordingly
check out the below Code for asking the permission
Future<bool> checkAndRequestCameraPermissions() async {
PermissionStatus permission =
await PermissionHandler().checkPermissionStatus(PermissionGroup.camera);
if (permission != PermissionStatus.granted) {
Map<PermissionGroup, PermissionStatus> permissions =
await PermissionHandler().requestPermissions([PermissionGroup.camera]);
return permissions[PermissionGroup.camera] == PermissionStatus.granted;
} else {
return true;
}
}
later only check if you have permission then do the required process.
if (await checkAndRequestCameraPermissions()) {
File image = await ImagePicker.pickImage(source: ImageSource.camera);
// continue with the image ...
}
for time being i have used the image_picker you can use Multi Image Picker.
check out the code and let me know.
Thanks.
Try to change the version of multi image picker it will work.. if you are using latest version and still received same problem then change it to old version.

How to use Steam (OpenId) to login into my Firebase powered Flutter app?

I'm building a Flutter app and I want users to be able to login through Steam (OpenId).
The app is powered by Firebase.
I'm pretty new to the whole OpenId world and I've read into it but I'm still not getting it.
I found that Firebase Supports signinWithCustomToken so I think I should get the Steam OpenId to get me one of those.
I also found two packages which might help me but I couldn't get those to work either:
https://pub.dev/packages/openid_client
https://pub.dev/packages/steam_login
If tried the following sample from the openid_client package:
_authenticate(Uri uri, String clientId, List<String> scopes) async {
try {
var issuer = await Issuer.discover(uri);
var client = Client(issuer, clientId);
print('CLAIMS:');
print(issuer.claimsMap);
urlLauncher(String url) async {
if (await canLaunch(url)) {
await launch(url, forceWebView: true);
} else {
throw 'Could not launch $url';
}
}
var authenticator = Authenticator(client,
scopes: scopes, port: 4000, urlLancher: urlLauncher);
var c = await authenticator.authorize();
closeWebView();
print(await c.getUserInfo());
}catch (err) {
print(err);
}
}
But I have no idea what to give as the uri, clientId and scopes.
For the uri I've tried https://steamcommunity.com/openid but when I try this I'm getting an error that it tried to Json.parse a xml response.
I've also tried the example for the steam_login package here, but that does nothing and doesn't feel like it should work within a Flutter app (even though the package states it Flutter compatible).
So if anybody could explain to me how I could achieve this with a working sample that would be great.
If I get this to work I'm planning on creating a tutorial/guide for it for others.