【问题标题】:type 'String' is not a subtype of type 'File'“字符串”类型不是“文件”类型的子类型
【发布时间】:2020-02-23 15:02:03
【问题描述】:

到目前为止,在我的应用中一切正常,除了我不断收到一个错误:

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

我尝试了很多方法来尝试解决问题,但仍未解决任何问题。

我能理解问题出在哪里,但我无数次尝试都无法解决它。

问题是我使用ImagePicker gallery 传递Image 我将该图像数据作为image: image.toString() 传递到firebase 并且它工作正常。 Firebase 采用路径,但我得到一个错误:_file != null,因为图像确实是File image 我无法从 firebase 获取数据并将字符串路径作为参数传递。因此收到此错误type 'String' is not a subtype of type 'File'。我在应用程序上显示图像,如下所示Image.file(image),因为它是显示文件图像并使用ImagePicker 的唯一方法。有解决方案吗?还是我试图实现的想法是一种不好的方式?

代码如下:

图像选择器:

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);
      });
    });
  }

提供者:

import: 'dart:io';

class AddCar {
  // other data
  File image;

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

firebase 数据:

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();
  }

我如何显示从 firebase 获取的数据:

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

我如何调用要在应用中显示的数据:

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,
                    );
                  },
                ),
              ),

当我运行应用程序时得到什么:

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)

【问题讨论】:

  • 你能出示你的代码吗?
  • @Lekr0 刚刚添加了一些代码检查一下
  • 请也提供堆栈跟踪
  • @Marc 刚刚在底部添加了一些内容,这就是您的意思吗??
  • 是的,这是一个堆栈跟踪

标签: firebase file flutter error-handling imagepicker


【解决方案1】:

似乎不是这样做:

image: carData['image']

你应该这样做:

image: File(carData['image'])

因为carData['image']String,而不是File,而AddCar 需要File

【讨论】:

  • 我试过了,得到以下错误: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")
  • 后跟这个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 ...
  • 价值 50 是从我的价格中调用的 TextFormField 我也尝试过 carData[File('image')], 但也没有用
  • 我无法帮助您,因为我没有看到 CarItem 的代码...
  • 我在“我如何调用要在应用程序中显示的数据:”部分显示它,除非你想要更多代码让我知道,以便我提供更多
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 2018-12-30
  • 1970-01-01
  • 2020-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多