Search code examples
fluttergallerypicker

_TypeError (type 'MediaFile' is not a subtype of type 'File' in type cast)


I want to store Mediafile in firebase storage but I think there is no method expect for File and Image Is it right ? All I see the firebase storage method is using ref.putFile or ref.putData .That's all for firebase storage method.I am beginner in flutter so there is somethings worng In my question please forgive me.

**Acutally all the code are from gallery_picker package

example,I copy the example and paste them to my project and just modify then I try to use it and try to put it to firebase storage here is the package which I try **

Here is my full code,

import 'dart:io';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:facebook_app/models/stories_model.dart';
import 'package:facebook_app/models/user_model.dart' as model;
import 'package:facebook_app/provider/user_provider.dart';
import 'package:facebook_app/screens/home_screen_layout.dart';
import 'package:facebook_app/services/image_storage.dart';

import 'package:firebase_auth/firebase_auth.dart';

import 'package:firebase_storage/firebase_storage.dart';

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

import 'package:provider/provider.dart';
import 'package:uuid/uuid.dart';

import '../provider/user_provider.dart';

// ignore: depend_on_referenced_packages

// import '../provider/user_provider.dart' as model;
// import '../provider/user_provider.dart';

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        brightness: Brightness.light,
        /* light theme settings */
      ),
      darkTheme: ThemeData(
        brightness: Brightness.dark,
        /* dark theme settings */
      ),
      themeMode: ThemeMode.dark,
      home: const MyHomePage(
        title: "Gallery Picker",
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final List<MediaFile>? medias;
  const MyHomePage({super.key, required this.title, this.medias});

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  List<MediaFile> selectedMedias = [];
  bool _isLoading = false;
  void Storytask(
    String uid,
    String profileUrl,
    String username,
  ) async {
    setState(() {
      _isLoading = true;
    });
    try {
      String res = await uploadPost(downloadUrls, uid, username, profileUrl);
      if (res == "success") {
        await Navigator.of(context).pushReplacement(
            MaterialPageRoute(builder: (context) => HomeScreenLayout()));
        setState(() {
          _isLoading = false;
        });
        showSnackBar('Posted', context);
      } else {
        setState(() {
          _isLoading = false;
        });
      }
    } catch (e) {
      showSnackBar(e.toString(), context);
    }
  }

  @override
  void initState() {
    if (widget.medias != null) {
      selectedMedias = widget.medias!;
    }
    super.initState();
  }

  int pageIndex = 0;
  var controller = PageController(initialPage: 0);
  @override
  Widget build(BuildContext context) {
    Provider.of<UserProvider>(context).refreshUser();
    final model.User? user = Provider.of<UserProvider>(context).getUser;
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pushReplacement(
              MaterialPageRoute(builder: (context) => HomeScreenLayout())),
        ),
        title: Text(widget.title),
        actions: [
          IconButton(
            icon: Icon(Icons.upload),
            onPressed: () async {
              for (int i = 0; i < selectedMedias.length; i++) {
                String url = await uploadFile(selectedMedias[i] as File);
                downloadUrls.add(url);
                if (i == selectedMedias.length - 1) {
                  Storytask(user?.uid ?? '', user?.photoUrl ?? '',
                      user?.username ?? '');
                }
              }
            },
          )
        ],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Spacer(),
            const Text(
              'These are your selected medias',
            ),
            const Divider(),
            Expanded(
              flex: 5,
              child: Stack(children: [
                if (selectedMedias.isNotEmpty)
                  PageView(
                    controller: controller,
                    children: [
                      for (var media in selectedMedias)
                        Center(
                          child: MediaProvider(
                            media: media,
                          ),
                        )
                    ],
                  ),
                if (selectedMedias.isNotEmpty)
                  Align(
                    alignment: Alignment.centerRight,
                    child: TextButton(
                        onPressed: () {
                          if (pageIndex < selectedMedias.length - 1) {
                            pageIndex++;
                            controller.animateToPage(pageIndex,
                                duration: const Duration(milliseconds: 500),
                                curve: Curves.easeIn);
                            setState(() {});
                          }
                        },
                        child: const Icon(
                          Icons.chevron_right,
                          size: 100,
                          color: Colors.red,
                        )),
                  ),
                if (selectedMedias.isNotEmpty)
                  Align(
                    alignment: Alignment.centerLeft,
                    child: TextButton(
                        onPressed: () {
                          if (pageIndex > 0) {
                            pageIndex--;
                            controller.animateToPage(pageIndex,
                                duration: const Duration(milliseconds: 500),
                                curve: Curves.easeIn);
                            setState(() {});
                          }
                        },
                        child: const Icon(
                          Icons.chevron_left,
                          size: 100,
                          color: Colors.red,
                        )),
                  ),
              ]),
            ),
            SizedBox(
              height: 65,
              child: ListView(
                scrollDirection: Axis.horizontal,
                children: [
                  for (int i = 0; i < selectedMedias.length; i++)
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 5),
                      child: TextButton(
                        onPressed: () {
                          pageIndex = i;
                          controller.animateToPage(pageIndex,
                              duration: const Duration(milliseconds: 500),
                              curve: Curves.easeIn);
                          setState(() {});
                        },
                        child: Container(
                            width: 65,
                            height: 50,
                            decoration: BoxDecoration(
                                border: Border.all(
                                    width: 2,
                                    color: pageIndex == i
                                        ? Colors.red
                                        : Colors.black)),
                            child: ThumbnailMedia(
                              media: selectedMedias[i],
                            )),
                      ),
                    )
                ],
              ),
            ),
            const Spacer(
              flex: 2,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: pickMedia,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }

  List<String> downloadUrls = [];
  Future<void> pickMedia() async {
    List<MediaFile>? media = await GalleryPicker.pickMedia(
        context: context,
        initSelectedMedia: selectedMedias,
        extraRecentMedia: selectedMedias,
        startWithRecent: true);
    if (media != null) {
      setState(() {
        selectedMedias += media;
      });
    }
  }

  Future<void> getGalleryMedia() async {
    // ignore: unused_local_variable
    GalleryMedia? allmedia = await GalleryPicker.collectGallery;
  }
}

Future<String> uploadFile(File file) async {
  final metaData = SettableMetadata(contentType: 'image/jpeg');
  final storageRef = FirebaseStorage.instance.ref();
  Reference ref =
      storageRef.child('pictures/${DateTime.now().microsecondsSinceEpoch}.jpg');
  final uploadTask = ref.putFile(file, metaData);

  final taskSnapshot = await uploadTask.whenComplete(() => null);
  String url = await taskSnapshot.ref.getDownloadURL();
  return url;
}

uploadPost(List<String> imageUrls, String uid, String username,
    String profileUrl) async {
  String res = "Some Errors occured";

  try {
    String postId = const Uuid().v1();
    Story post = Story(
        postMediaFileUrl: imageUrls,
        profileUrl: profileUrl,
        uid: uid,
        username: username);
    FirebaseFirestore.instance
        .collection('stories')
        .doc(postId)
        .set(post.toJson());
    // Navigator.of(context).pushReplacement(
    //     MaterialPageRoute(builder: (context) => HomeScreenLayout()));
    res = "success";
  } catch (e) {
    res = e.toString();
  }
  return res;
}

Solution

  • Maybe the problem is in String url = await uploadFile(selectedMedias[i] as File);

    Update the section where you upload media files.

    for (int i = 0; i < selectedMedias.length; i++) {
      String filePath = _selectedDocument.path; // Replace with the correct way to obtain the file path from your MediaFile
      File file = File(filePath); // Convert file path to File
      String url = await uploadFile(file); // Upload the File to Firebase Storage
      downloadUrls.add(url);
      if (i == selectedMedias.length - 1) {
        Storytask(user?.uid ?? '', user?.photoUrl ?? '', user?.username ?? '');
      }
    }