Custom action to export a collection as txt file

I have created a custom action that you can adapt if you need to export the data of a Firebase collection as a txt file.

You have to make sure you send the collection you want to export to the custom action, plus add the dependency as it's shown on the next image, you can find the information about it here https://pub.dev/packages/download/versions/0.0.1+1.

In the created example, in the button a backend query is made to get the collection and at the moment of executing the customized action, as shown in the following image, the collection is sent as a parameter.

Finally, the code for the custom action would be as follows:

// Automatic FlutterFlow imports
import '/backend/backend.dart';
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!

import 'dart:convert'show utf8; // Import the "dart:convert" package to work with UTF-8 character encoding and decoding.
import 'package:download/download.dart'; // Import the package containing the "download" function to download files.

// The exportarATxt function takes a list of objects of type "ProductosRecord"
// and returns a Future (future object) as a result.
Future exportarATxt(List<ProductosRecord> coleccion) async {

  // If the product list is null, it is initialized as an empty list.
  coleccion = coleccion ?? [];

  // Creation of the text file header, in this case without content.
  String fileContent = "";

  // Runs through the list of products and adds each product to the content of the text file.
  coleccion.asMap().forEach((index, producto) => fileContent = fileContent +
      "name: " +
      producto.name.toString() +
      "\n" +
      "description: " +
      producto.description.toString() +
      "\n" +
      "price: " +
      producto.price.toString() +
      "\n" +
      "quantity: " +
      producto.quantity.toString() +
      "\n\n"); //You can change these lines above according to the data you want to export and the details you want to display in the file.

// Creates a file name based on the current date and time.
  final fileName = "Datos de colección " + DateTime.now().toString() + ".txt";

  // Encodes the contents of the file as a UTF-8 byte list.
  var bytes = utf8.encode(fileContent);

  // Creates a Stream from the byte list to be used in the "download" function.
  final stream = Stream.fromIterable(bytes);

  // Download the file using the contents of the Stream and the file name provided.
  return download(stream, fileName);
}

The result of the code above would look like this:

#FidelitasUniversity

7
4 replies