Skip to content

Best Practice

Midori edited this page Jun 25, 2023 · 34 revisions

Let's see this code in example.

_Button(
  onPressed: () async {
    final requestGranted = await Gal.requestAccess();
    if (requestGranted) {
      final path = await getFilePath('assets/done.jpg');
      try {
        await Gal.putImage(path);
      } on GalException catch (e) {
        log(e.toString());
      }
      return;
    }
    if (!context.mounted) return;
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text("Unable to save"),
        content: const Text(
            "Please allow access to the Photos app."),
        actions: [
          TextButton(
            child: const Text("OK"),
            onPressed: () => Navigator.pop(context),
          ),
        ],
      ),
    );
  },
  label: 'Best Practice',
  icon: Icons.done,
),

Here is an explanation of what we are doing here.

  1. When the button is pressed, it requests access to the gallery app.

    The results of access requests vary in detailed behavior depending on the OS type and version. To learn more, please see Permissions.

  2. If the request is granted, the image saving process begins with error handling provided by try-catch.

    Error handling is recommended in the production code in case an image format not supported by the OS is passed.

  3. If access is denied, a dialog requesting access is displayed.

    For more user friendliness, you may want to put a button that jumps to the app settings using url_laucher or something.

Clone this wiki locally