2

So far in my app everything is working except that one error I keep getting:

type 'String' is not a subtype of type 'File'

I tried many ways to try and fix the Issue but nothing has yet been resolved.

I can understand where the issue is, but I'm unable to fix it with countless attempts.

The problem is that im passing an Image using ImagePicker gallery im passing that image data to firebase as image: image.toString() and it works fine. Firebase takes the path but as an error i get: _file != null since the image is indeed a File image I cant fetch the data from firebase and pass the string path as an argument. therefore getting this error type 'String' is not a subtype of type 'File'. I display the image on the app like the following Image.file(image) Since its the only way to display a File image and use the ImagePicker. Is there a solution for this? or is it a bad way of doing the idea im trying to achieve?

here is the code:

image picker:

String img;

  static Future<String> fileToB64(File f) async {
    List<int> imageBytes = f.readAsBytesSync();

    return base64Encode(
      imageBytes,
    );
  }

  Future<void> _takePicture() async {
    final imageFile = await ImagePicker.pickImage(
      source: ImageSource.gallery,
    );
    setState(() {
      data.image = imageFile;
    });
    fileToB64(imageFile).then((d) {
      setState(() {
        img = d; //base64Decode(d);
      });
    });
  }

the provider:

import: 'dart:io';

class AddCar {
  // other data
  File image;

  AddCar({
    this.// other data
    this.image,
  });
}

firebase data:

Future<void> fetchAndSetCars() async {
    const url = 'https://mylink.firebaseio.com/cars.json';
    try {
      final response = await http.get(url);
      final extractedData = json.decode(response.body) as Map<String, dynamic>;
      final List<AddCar> loadedCars = [];
      extractedData.forEach((carId, carData) {
        loadedCars.add(AddCar(
          // other data
          image: carData['image'],
        ));
      });
      _cars = loadedCars;
      notifyListeners();
    } catch (error) {
      throw (error);
    }
  }

  AddCar findById(String id) {
    return _cars.firstWhere((carProd) => carProd.id == id);
  }

  void addCar(AddCar car) {
    const url = 'https://mylink.firebaseio.com/cars.json';
    http.post(
      url,
      body: json.encode({
        // other data
        'image': car.image.toString(),
      }),
    );
    final newCar = AddCar(
    // other data
      image: car.image,
    );
    _cars.insert(0, newCar); // add car at the top of the list
    notifyListeners();
  }

how im displaying the fetch data from firebase:

 @override
  void initState() {
 Future.delayed(Duration.zero).then((_) {
  Provider.of<Cars>(context).fetchAndSetCars();
 });
    super.initState();
  }

how im calling the data to be displayed in the app:

Container(
                width: MediaQuery.of(context).size.width * 0.35,
                height: MediaQuery.of(context).size.width * 0.35,
                child: GestureDetector(
                  child: Image.file(
                    image,
                    fit: BoxFit.fill,
                  ),
                  onTap: () {
                    Navigator.of(context).pushNamed(
                      MyCarDetails.routeName,
                      arguments: id,
                    );
                  },
                ),
              ),

What I get when I run the app:

Restarted application in 6,085ms.
E/flutter ( 3497): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type 'String' is not a subtype of type 'File'
E/flutter ( 3497): #0      Cars.fetchAndSetCars 
package:flutter_app/providers/car_provider.dart:54
E/flutter ( 3497): <asynchronous suspension>
E/flutter ( 3497): #1      _CarAreaState.initState.<anonymous closure> 
package:flutter_app/home_parts/cars_area.dart:28
E/flutter ( 3497): #2      _rootRunUnary  (dart:async/zone.dart:1132:38)
E/flutter ( 3497): #3      _CustomZone.runUnary  (dart:async/zone.dart:1029:19)
E/flutter ( 3497): #4      _FutureListener.handleValue  (dart:async/future_impl.dart:137:18)
E/flutter ( 3497): #5      Future._propagateToListeners.handleValueCallback  (dart:async/future_impl.dart:678:45)
E/flutter ( 3497): #6      Future._propagateToListeners  (dart:async/future_impl.dart:707:32)
E/flutter ( 3497): #7      Future._complete  (dart:async/future_impl.dart:512:7)
E/flutter ( 3497): #9      _rootRun  (dart:async/zone.dart:1120:38)
E/flutter ( 3497): #10     _CustomZone.run  (dart:async/zone.dart:1021:19)
E/flutter ( 3497): #11     _CustomZone.runGuarded  (dart:async/zone.dart:923:7)
E/flutter ( 3497): #12     _CustomZone.bindCallbackGuarded.<anonymous closure>  (dart:async/zone.dart:963:23)
E/flutter ( 3497): #13     _rootRun  (dart:async/zone.dart:1124:13)
E/flutter ( 3497): #14     _CustomZone.run  (dart:async/zone.dart:1021:19)
E/flutter ( 3497): #15     _CustomZone.bindCallback.<anonymous closure>  (dart:async/zone.dart:947:23)
E/flutter ( 3497): #16     Timer._createTimer.<anonymous closure>  (dart:async-patch/timer_patch.dart:21:15)
E/flutter ( 3497): #17     _Timer._runTimers  (dart:isolate-patch/timer_impl.dart:382:19)
E/flutter ( 3497): #18     _Timer._handleMessage  (dart:isolate-patch/timer_impl.dart:416:5)
E/flutter ( 3497): #19     _RawReceivePortImpl._handleMessage  (dart:isolate-patch/isolate_patch.dart:172:12)

2 Answers2

3

It seems that instead of doing this:

image: carData['image']

You should do this:

image: File(carData['image'])

Because carData['image'] is a String, not a File, and AddCar expects a File.

Pablo Barrera
  • 10,387
  • 3
  • 28
  • 49
  • I tried that and got the following error: `The following NoSuchMethodError was thrown building CarItem(dirty, dependencies: [_LocalizationsScope-[GlobalKey#5f0e8], _InheritedTheme, MediaQuery]): The method '+' was called on null. Receiver: null Tried calling: +("50")` –  Oct 28 '19 at 10:55
  • followed by this `User-created ancestor of the error-causing widget was ListView lib\home_parts\cars_area.dart:67 When the exception was thrown, this was the stack #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5) #1 CarItem.build package:flutter_app/widget/car_item.dart:151 #2 StatelessElement.build package:flutter/…/widgets/framework.dart:4009 #3 ComponentElement.performRebuild package:flutter/…/widgets/framework.dart:3941 #4 Element.rebuild package:flutter/…/widgets/framework.dart:3738 ...` –  Oct 28 '19 at 10:56
  • the value `50` was called from my price `TextFormField` I also tried `carData[File('image')],` but didnt work either –  Oct 28 '19 at 10:58
  • I can't help you with that because I don't see the code of CarItem... – Pablo Barrera Oct 28 '19 at 11:01
  • Im showing it in the "how im calling the data to be displayed in the app:" part unless you want more code let me know so i can provide more –  Oct 28 '19 at 11:02
  • It seems that the problem of your question was solved and now you're facing another problem. You could try a little more to solve it and then if you are stuck ask another question. By the way, the CarItem is not in the code you posted. – Pablo Barrera Oct 28 '19 at 11:05
  • Ah i see. I did post a snippet of how im displaying the image in the CarItem. you are correct I didnt include the entire CarItem becasue its an entire page of code and I just wanted to highlight the image displaying way im using –  Oct 28 '19 at 11:08
  • Also got this error i didnt see. `E/flutter ( 3497): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: A Cars was used after being disposed. E/flutter ( 3497): Once you have called dispose() on a Cars, it can no longer be used.` –  Oct 28 '19 at 11:10
  • Please, spent some time trying to solve these issues and then if you can't ask another question. – Pablo Barrera Oct 28 '19 at 11:12
0

sometimes it's because of using ! null safety you should run like flutter run --no-sound-null-safety

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 11 '22 at 04:04