Dan
ย ยทย Browse Poster

Download an image and store locally on phone in a data schema

Troubleshooting

Hi FF Community,

I am trying to download images that is shown in my app and save them locally on the phone or in a data schema to be shown should there be no signal.

I have created an action, but not sure if this is the right approach and I do not get a return value.

The images are shown in the app via an api call to my database. This is the images I would then like to save on the phone and then be able to show again should the phone be without internet.

What have you tried so far?
// Automatic FlutterFlow imports
import '/backend/schema/structs/index.dart';
import '/actions/actions.dart' as action_blocks;
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/actions/index.dart'; // Imports other custom actions
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom action code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

// Additional imports required for the custom action
import 'package:http/http.dart' as http;
import 'dart:io';
import 'dart:convert';
import 'package:path_provider/path_provider.dart';

Future<String?> downloadImage(String? image) async {
  // download image to save locally and return base64 string
  if (image == null) {
    return null;
  }

  try {
    final response = await http.get(Uri.parse(image));
    if (response.statusCode == 200) {
      final bytes = response.bodyBytes;

      final directory = await getApplicationDocumentsDirectory();
      final file = File('${directory.path}/image.png');
      await file.writeAsBytes(bytes);

      final imageBytes = await file.readAsBytes();
      final base64Image = base64Encode(imageBytes);

      return base64Image;
    } else {
      print('Error: ${response.statusCode}');
      return null;
    }
  } catch (e) {
    print(e);
    return null;
  }
}
Did you check FlutterFlow's Documentation for this topic?
Yes
2