تحمل ورفع ملف من الانترنت مع اظهار شريط التحميل اثناء التحميل و الرفع في flutter

تحمل ورفع ملف من الانترنت مع اظهار شريط التحميل اثناء التحميل و الرفع في flutter

تحمل ورفع ملف من الانترنت مع اظهار شريط التحميل اثناء التحميل و الرفع في flutter

في هذه المقالة سوف نشرح معكم كيف تقوم بامكانية رفع وتحميل ملف باستخدام api مع اظهار نسبة الرفع او حتى نسبة التحميل مع اظهار notification يوضح حالة التحميل او الرفع الخاصه بالعنصر الذي قمت بعمله كما هو موضح بالصورة الخاصه بالمقالة وهذا الامر بسيط جدا وكل شيئ موجود بداخل مكتبة dio فلن نحتاج الى اي مكتبات خاريجة اخرى سوا local notification حتى نعرض الاشعار ولكن اذا لم تكن تريد عرض اشعار وفقط تريد عرض شريط في التطبيق يوضح حالة الملف فيمكنك ذلك بدون استخدام مكتبة الاشعارات .


إن حرفة تطوير تطبيقات الأجهزة المحمولة تتطلب عمالة مكثفة وتغير العالم الرقمي يوميًا. بناء البرمجيات للأجهزة المحمولة هو ما يستلزمه. تقنيات المعالجة الدقيقة المتقدمة مطلوبة لإنشاء تطبيقات الهاتف المحمول. وقد رفعت هذه التقنيات من مستوى إنشاء برامج الهاتف المحمول. على سبيل المثال ، يمكنك الآن تشغيل تطبيقات الأجهزة المحمولة على مجموعة متنوعة من الأنظمة الأساسية. بالإضافة إلى ذلك ، يتم إنشاء أفضل تطبيقات سطح المكتب للهواتف الذكية.


تطبيقات الأجهزة المحمولة التي تم إنشاؤها متاحة للتنزيل والتثبيت المسبق على أجهزة Android و iPhone. يمكن لكل من أجهزة Mac وأجهزة الكمبيوتر التي تعمل بنظام Windows الاستجابة لها. يستكشف المطورون الحقائق المتعلقة باستهلاك تطبيقات الأجهزة المحمولة لإنشاء تطبيقات الأجهزة المحمولة. يأخذون في الاعتبار مقدار الأموال التي ينفقها المستخدمون على هواتفهم الذكية وإمكانية تطوير تطبيقات الهاتف المحمول.



How to downloading and uploading in Flutter

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


How to downloading and uploading in Flutter

codes.dart


import 'dart:math';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';


// تهيئة الاشعارات لتعمل على التطبيق
Future<void> notificationInitialization() async {
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  const AndroidInitializationSettings initializationSettingsAndroid =
  AndroidInitializationSettings('@mipmap/ic_launcher');

  const InitializationSettings initializationSettings =  InitializationSettings(
      android: initializationSettingsAndroid);

  await flutterLocalNotificationsPlugin.initialize(initializationSettings);
}

// اشعارات مخصصه في حالة الرفع
Future<void> uploadingNotification(maxProgress, progress , isUploading) async {
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  if(isUploading){
    final AndroidNotificationDetails androidPlatformChannelSpecifics =
    AndroidNotificationDetails(
        "uploading files",
        "Uploading Files Notifications",
        channelDescription: "show to user progress for uploading files",
        channelShowBadge: false,
        importance: Importance.max,
        priority: Priority.high,
        onlyAlertOnce: true,
        showProgress: true,
        maxProgress: maxProgress,
        progress: progress,
        autoCancel: false
    );

    // في حالة رفع الملف
    NotificationDetails platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(
      5,
      'Uploading file',
      '',
      platformChannelSpecifics,
    );
  }else{

    flutterLocalNotificationsPlugin.cancel(5);
    AndroidNotificationDetails androidPlatformChannelSpecifics =
    const AndroidNotificationDetails(
      "files",
      "Files Notifications",
      channelDescription: "Inform user files uploaded",
      channelShowBadge: false,
      importance: Importance.max,
      priority: Priority.high,
      onlyAlertOnce: true,
    );

    // عندما يتم رفع الملف
    NotificationDetails platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(
      Random().nextInt(1000000),
      'file uploaded',
      '',
      platformChannelSpecifics,
    );
  }



}

// اشعارات مخصصه في حالة التحميل
Future<void> downloadingNotification(maxProgress, progress , isDownloaded) async {
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  if(!isDownloaded){
    final AndroidNotificationDetails androidPlatformChannelSpecifics =
    AndroidNotificationDetails(
        "downloading files",
        "downloading Files Notifications",
        channelDescription: "show to user progress for downloading files",
        channelShowBadge: false,
        importance: Importance.max,
        priority: Priority.high,
        onlyAlertOnce: true,
        showProgress: true,
        maxProgress: maxProgress,
        progress: progress,
        autoCancel: false
    );


    NotificationDetails platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(
      6,
      'Downloading file',
      '',
      platformChannelSpecifics,
    );
  }else{

    flutterLocalNotificationsPlugin.cancel(6);
    AndroidNotificationDetails androidPlatformChannelSpecifics =
    const AndroidNotificationDetails(
      "files",
      "Files Notifications",
      channelDescription: "Inform user files downloaded",
      channelShowBadge: false,
      importance: Importance.max,
      priority: Priority.high,
      onlyAlertOnce: true,


    );


    NotificationDetails platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(
      Random().nextInt(1000000),
      'File Downloaded',
      '',
      platformChannelSpecifics,
    );
  }

}


كيفية الرفع والتحميل من الانترنت باستخدام مكتبة dio مع تحديد مدة التحميل

كيفية الرفع والتحميل من الانترنت باستخدام مكتبة dio مع تحديد مدة التحميل

ui.dart


import 'dart:io';
import 'package:dio/dio.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:open_file/open_file.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:untitled/pages/uploading_downloading/Utils.dart';
import 'package:untitled/pages/uploading_downloading/notifications.dart';

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  bool isLoadingUploading = false;
  bool isLoadingDownloading = false;
  String valeUploading = '0';
  String valeDownloading = '0';
  Dio dio = Dio();
  Directory directory = Directory("storage/emulated/0/AM");
  String urlDownload =
      'https://snapcreek.com/wp-content/uploads/blog-large-site-dinosaur.jpg';

  
  // رفع ملف على السيرفر
  Future<void> uploadFile(filePath) async {
    var postUrl = 'https://bego88.000webhostapp.com/upload.php';
    String fileName = filePath.split('/').last;
    debugPrint("File Path$filePath");

    FormData formData = FormData.fromMap({
      "fileToUpload":
          await MultipartFile.fromFile(filePath, filename: fileName),
    });

    try {
      final response = await dio.post(
        postUrl,
        data: formData,
        onSendProgress: (count, total) {
          uploadingNotification(total, count, true);

          setState(() {
            isLoadingUploading = true;
            valeUploading = ((count / total) * 100).toStringAsFixed(0);
          });
        },
      ).whenComplete(() {
        uploadingNotification(0, 0, false);
        setState(() {
          isLoadingUploading = false;
        });
      });
      // ignore: use_build_context_synchronously
      buildShowSnackBar(context, "file uploaded");
      debugPrint('file : ${response.data}');
    } catch (e) {
      debugPrint('exception $e');
    }
  }

  // تحميل ملف من الانترنت
  Future<void> downloadFile(fileUrl, filePath) async {
    print('urls ------------ $fileUrl');

    String fileName = fileUrl.split('/').last;
    print(fileName);
    print('$filePath/$fileName');
    print('------------------');

    // التاكد من الملف هل تم تحميله مسبقا ام لا
    await isFileDownloaded(fileName)
        ? OpenFile.open("$filePath/$fileName")
        : 
     //تحميل الملف مع تحديد المسار ومدة التحميل 
    dio.download(
            fileUrl,
            "$filePath/$fileName",
            onReceiveProgress: (count, total) {
              downloadingNotification(total, count, false);

              setState(() {
                isLoadingDownloading = true;
                valeDownloading = ((count / total) * 100).toStringAsFixed(0);
              });
            },
          ).whenComplete(() {
            downloadingNotification(0, 0, true);
            setState(() {
              isLoadingDownloading = false;
            });
          });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            if (!isLoadingUploading)
              ElevatedButton(
                  onPressed: () async {
                    FilePickerResult? result =
                        await FilePicker.platform.pickFiles();
                    if (result != null) {
                      uploadFile(result.files.single.path);
                    }
                  },
                  child: const Text("Upload File To Server")),
            if (isLoadingUploading)
              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: (int.parse(valeUploading) / 100),
                  ),
                ),
              ),
            if (!isLoadingDownloading)
              ElevatedButton(
                  onPressed: () async {
                    Directory directory = Directory(path);

                    var state = await Permission.manageExternalStorage.status;
                    var state2 = await Permission.storage.status;

                    if (!state2.isGranted) {
                      await Permission.storage.request();
                    }
                    if (!state.isGranted) {
                      await Permission.manageExternalStorage.request();
                    }
                    if (!await directory.exists()) {
                      // اذا لم يكن المسار موجود من قبل فنقوم بعملة ومن ثم تحميل الملف
                      await directory.create();
                      downloadFile(
                          "https://cdn.pixabay.com/photo/2018/04/09/19/55/low-poly-3305284__340.jpg",
                          directory.path);
                    } else {
                      // تحميل الملف اذا كان المسار موجود سابقا
                      downloadFile(
                          "https://cdn.pixabay.com/photo/2018/04/09/19/55/low-poly-3305284__340.jpg",
                          directory.path);
                    }
                  },
                  child: const Text("Download File From Server")),
            if (isLoadingDownloading)
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: Row(
                  children: [
                    Expanded(
                      child: Container(
                        clipBehavior: Clip.hardEdge,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(5),
                          color: Colors.blue.shade50,
                        ),
                        child: LinearProgressIndicator(
                          value: (int.parse(valeDownloading) / 100),
                        ),
                      ),
                    ),
                    const SizedBox(
                      width: 5,
                    ),
                    Text('$valeDownloading%'),
                  ],
                ),
              ),
          ],
        ),
      ),
      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

تعليقات