Flutter | Пакет Dio ... загрузка больших файлов в фоновом режиме

Я использую flutter с пакетом dio для загрузки файлов, таких как powerpoint, видео и т. Д.

что я хочу спросить, так это как загрузить большой файл в фоновом режиме

try {
    await dio.download(
        fileURL, '$dir/$fileName.pptx',
        onReceiveProgress: showDownloadProgress,
        deleteOnError: true);
    print("BBBB");

    openDownloadedFile = '$dir/$fileName.pptx';
    print("CCCC");
  } on DioError catch(e) {
    print("11");

    final file = File('$dir/$fileName.pptx');
    file.deleteSync(recursive: true);
    if(e.response != null) {
      print("22");

      print(e.response.data);
      print(e.response.headers);
      print(e.response.request);
    } else{

      // Something happened in setting up or sending the request that triggered an Error
      print(e.request);
      print(e.message);
    }
  }

С наилучшими пожеланиями

2 ответа

Поскольку этот вопрос был задан, во Flutter есть официальная поддержка фоновых задач. Вы можете проверить это сейчас.

Ссылка на документы: https://docs.flutter.dev/development/packages-and-plugins/background-processes

Пример ссылки: https://flutteragency.com/schedule-background-tasks/

Полный пример (из документов)

      import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    const title = 'WebSocket Demo';
    return const MaterialApp(
      title: title,
      home: MyHomePage(
        title: title,
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({
    super.key,
    required this.title,
  });

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController _controller = TextEditingController();
  final _channel = WebSocketChannel.connect(
    Uri.parse('wss://echo.websocket.events'),
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Form(
              child: TextFormField(
                controller: _controller,
                decoration: const InputDecoration(labelText: 'Send a message'),
              ),
            ),
            const SizedBox(height: 24),
            StreamBuilder(
              stream: _channel.stream,
              builder: (context, snapshot) {
                return Text(snapshot.hasData ? '${snapshot.data}' : '');
              },
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _sendMessage,
        tooltip: 'Send message',
        child: const Icon(Icons.send),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  void _sendMessage() {
    if (_controller.text.isNotEmpty) {
      _channel.sink.add(_controller.text);
    }
  }

  @override
  void dispose() {
    _channel.sink.close();
    _controller.dispose();
    super.dispose();
  }
}

Я бы посоветовал вам использовать плагин Flutter Downloader для загрузки больших файлов, поскольку он использует собственный менеджер загрузок. Dio больше подходит для загрузки небольших файлов, когда приложение открыто.

Другие вопросы по тегам