شرح كيفية تحميل ملف من الانترنت في flutter مع اظهار نسبة التحميل

شرح كيفية تحميل ملف من الانترنت في flutter مع اظهار نسبة التحميل

شرح كيفية تحميل ملف من الانترنت في flutter مع اظهار نسبة التحميل

في هذه المقالة سوف نشرح كيف تقوم بتحميل اي ملف من الانترنت مع تحديد نسبة التحميل اثناء تحميل الملف ومعرفة النسبة المئوية التي وصل لها الملف اثناء تحميله كما نشاهد في باقي مواقع التواصل الاجتماعي او التطبيقات التي بها ملفات تحتاج الى التحميل وكل هذا سوف يكون من خلال هذه المقالة فيجب عليكم متابعة المقالة الى النهايه حتى لا يحدث معكم اي مشاكل اثناء استخدام المكتبة واثناء استخدام الكود والامر بسيط جدا عليكم في البداية استعامل مكتبة dio و path لتحويل مسار الملف الى مسار معين بداخل جهازك .


Native ARM هي إحدى ميزات Flutter المفيدة للشركات الناشئة والشركات التقنية. يمكّنك من تنفيذ فكرتك وجني ثمارها الكاملة لمشاريعك اللاحقة. سيجد المستخدمون أنه من الأسهل قراءة مواد الويب في تطبيقات الهاتف بفضل هذه الخصائص. يسهل Flutter أيضًا تثبيت التطبيق والتنقل. ثم تبين أن أحدث ترقية لـ Dart.2.2 قد غيرت قواعد اللعبة. تحسين أداء التعليمات البرمجية المترجمة AOT. يتوفر أيضًا عدد من فئات المجموعات في مكتبة dart لنمذجة الخرائط والقوائم ومجموعات الكائنات. تتيح الميزة إمكانية متابعة المعاملة في تطبيقك عندما يبدأ المستخدم واحدة في متجر التطبيقات.


  dio: ^4.0.6

  path_provider: ^2.0.11


How to download any file from internet in Flutter

الكود التالي لدينا ملف من الانترنت بصيغة pdf نريد تحميل هذا الملف وارفاقه بداخل الجهاز ومعرفة النسبة المئوية التي تتم في التطبيق خلال التحميل في البداية نقوم باستخدام getExternalStoragePath حتى نقوم بتحديد مسار معين لتنزيل الملف بداخله وبعدها تم استخدام downloadAndSaveFile وبداخلها نضع رابط الملف والاسم الذي نرغب بوضعه له ونستخدم خاصية onReceiveProgress لمعرفة حالة التحميل والنسبة المئوية التي وصل لها الملف اثناء عملية التنزيل من الانترنت واذا اكتملت العملية نقوم بتغيير قيمة التحميل الى false حتى يختفي الشريط الخاص بالتحميل وتتغير قيمة تحميل الملف ليظهر علامه ان الملف تم تحميله .


How to download any file from internet in Flutter

ui.dart


import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart' as provider;

class DownloadingPage extends StatefulWidget {
  const DownloadingPage({Key? key}) : super(key: key);

  @override
  State<DownloadingPage> createState() => _DownloadingPageState();
}

class _DownloadingPageState extends State<DownloadingPage> {
  bool isLoading = false;
  bool isDone = false;
  bool isStart = false;
  String urlPdf = 'http://www.pdf995.com/samples/pdf.pdf';
  String progress = '';
  int progressValue = 0;
  String fileFullPath = '';
  Dio? dio;

  Future<List<Directory>?> _getExternalStoragePath() async {
    return provider.getExternalStorageDirectories(type: provider.StorageDirectory.documents);
  }

  Future _downloadAndSaveFile(String url,String fileName) async {
    try {
      final dirList = await _getExternalStoragePath();
      final dir = dirList![0].path;
      final file = File('$dir/$fileName');
      await dio!.download(url, file.path, onReceiveProgress: (rec, total) {
        setState(() {
          isLoading = true;
          isStart = false;
          progress = '${((rec / total) * 100).toStringAsFixed(0)}%';
          progressValue = ((rec / total) * 100).toInt();
          print('Rec: $rec , Total: $total');
          print('progress: $progress');

          if (rec == total) {
            setState(() {
              isLoading = false;
              isDone = true;
              fileFullPath = file.path;
              print('fileFullPath: $fileFullPath');
              print('dir: $dir');
            });
          }

        });
      });
    } catch (e) {
      print(e);
    }
  }


  @override
  void initState() {
    dio = Dio();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (isStart)
              const CircularProgressIndicator(),
            if (!isStart)
            ElevatedButton(
                onPressed: (){
                  _downloadAndSaveFile(urlPdf, 'test.pdf');
                  setState(() {
                    isStart = true;
                  });
                },
                child: const Text('Download')
            ),
            const SizedBox(height: 20,),
            Text(progress),
            buildUploadFile(),
          ],
        ),
      ),
    );
  }
  Widget buildUploadFile() {
    return !isLoading ? Column(
      children: [
        const SizedBox(height: 5,),
        Container(
            clipBehavior: Clip.hardEdge,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                color: isDone ? Colors.green.shade50 : Colors.red.shade50
            ),
            child:  Padding(
              padding: EdgeInsets.all(5.0),
              child: Text(isDone ? 'downloaded' : 'not download', style: TextStyle(fontSize: 14),),
            ))
      ],
    ) : Padding(
      padding: const EdgeInsets.all(15.0),
      child: Container(
        // height: 5,
        clipBehavior: Clip.hardEdge,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5),
          color: Colors.blue.shade50,
        ),
        child: LinearProgressIndicator(
          value: progressValue / 100,
        ),
      ),
    );
  }
}


تعليقات