如何在Flutter Web中下载生成的csv文件

qoefvg9y  于 10个月前  发布在  Flutter
关注(0)|答案(2)|浏览(101)

我将使用http://pub.dev/packages/csv生成一个cvs文件。
一旦完成,并存储在字符串变量中,如何在Flutter Web上单击按钮下载它?
谢谢

j8yoct9x

j8yoct9x1#

以下是您正在寻找的完整工作解决方案:

  • 第一步:*

首先,你需要在Flutter项目中安装两个包:

  1. csv
  2. file_saver
    如下面的pubspec.yml文件所示:
name: csvwebdemo
description: A new Flutter project.
publish_to: 'none'
version: 0.1.0

environment:
  sdk: '>=3.1.0 <4.0.0'

dependencies:
  csv: ^5.0.2
  file_saver: ^0.2.8
  flutter:
    sdk: flutter

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^2.0.0

flutter:
  uses-material-design: true
  • 第二步:*

从我的代码中复制downloadCSV函数,在下载按钮中调用该函数,并在其中传递CSV字符串。
以下是我的完整代码供您参考:

import 'package:flutter/material.dart';

// add following imports
import 'dart:convert';
import 'dart:typed_data';
import 'package:csv/csv.dart';
import 'package:file_saver/file_saver.dart';

void main() {
  runApp(const MainApp());
}

class MainApp extends StatefulWidget {
  const MainApp({super.key});

  @override
  State<MainApp> createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  // Test CSV created just for demo.
  String csv = const ListToCsvConverter().convert(
    [
      ["Column1", "Column2"],
      ["Column1", "Column2"],
      ["Column1", "Column2"],
    ],
  );

  // Download and save CSV to your Device
  downloadCSV(String file) async {
    // Convert your CSV string to a Uint8List for downloading.
    Uint8List bytes = Uint8List.fromList(utf8.encode(file));

    // This will download the file on the device.
    await FileSaver.instance.saveFile(
      name: 'document_name', // you can give the CSV file name here.
      bytes: bytes,
      ext: 'csv',
      mimeType: MimeType.csv,
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child:
              // Download button UI code
              TextButton(
            onPressed: () async {
              //When the download button is pressed, call `downloadCSV` function and pass the CSV string in it.
              await downloadCSV(csv);
            },
            child: const Text(
              'Download',
            ),
          ),
        ),
      ),
    );
  }
}

输出:

下面是下载的文件的样子:

iyfjxgzm

iyfjxgzm2#

我已经成功地使用了file_saver包。
安装套件:

flutter pub add file_saver

Dart代码:

// Your csv string
String myCsv = '...';

// Convert it to bytes
List<int> encodedCsv = utf8.encode(source);
Uint8List csvBytesList = Uint8List.fromList(list);

// Issue the save call!
String path = await FileSaver.instance.saveFile(
   name: 'Name of File',
   bytes: csvBytesList,
   ext: 'csv',
   mimeType: MimeType.csv,
);

相关问题