0

Image.file我在从我的应用程序中调用 an 时遇到问题firebase。我尝试将它转换为字符串和很多东西,但没有任何效果。

这是我从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: File(carData['image']),
        ));
      });
      _cars = loadedCars;
      notifyListeners();
    } catch (error) {
      throw (error);
    }
  }

这是我传递给firebase的数据:(我转换了Image.toString()这是将文件传递给firebase以调用它的错误方式吗?)

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

    notifyListeners();
  }

以下是图像应该如何使用Image.file

 child: Image.file(
                    image,
                    fit: BoxFit.fill,
                  ),

最后使用从图库ImagePicker中选择:file Image

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 button in my code
 child: FlatButton(
                      child: Text(AppLocalizations.of(context).createAddImages),
                      onPressed: _takePicture,
                    ),

这是堆栈跟踪:

Restarted application in 3,377ms.
E/flutter (12041): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method 'forEach' was called on null.
E/flutter (12041): Receiver: null
E/flutter (12041): Tried calling: forEach(Closure: (String, dynamic) => Null)
E/flutter (12041): #0      Mobiles.fetchAndSetMobiles 
package:flutter_app/providers/mobile_provider.dart:180
E/flutter (12041): <asynchronous suspension>
E/flutter (12041): #1      _MobilesAreaState.initState.<anonymous closure> 
package:flutter_app/home_parts/mobiles_area.dart:17
E/flutter (12041): #2      _rootRunUnary  (dart:async/zone.dart:1132:38)
E/flutter (12041): #3      _CustomZone.runUnary  (dart:async/zone.dart:1029:19)
E/flutter (12041): #4      _FutureListener.handleValue  (dart:async/future_impl.dart:137:18)
E/flutter (12041): #5      Future._propagateToListeners.handleValueCallback  (dart:async/future_impl.dart:678:45)
E/flutter (12041): #6      Future._propagateToListeners  (dart:async/future_impl.dart:707:32)
E/flutter (12041): #7      Future._complete  (dart:async/future_impl.dart:512:7)
E/flutter (12041): #8      new Future.delayed.<anonymous closure>  (dart:async/future.dart:313:16)
E/flutter (12041): #9      _rootRun  (dart:async/zone.dart:1120:38)
E/flutter (12041): #10     _CustomZone.run  (dart:async/zone.dart:1021:19)
E/flutter (12041): #11     _CustomZone.runGuarded  (dart:async/zone.dart:923:7)
E/flutter (12041): #12     _CustomZone.bindCallbackGuarded.<anonymous closure>  (dart:async/zone.dart:963:23)
E/flutter (12041): #13     _rootRun  (dart:async/zone.dart:1124:13)
E/flutter (12041): #14     _CustomZone.run  (dart:async/zone.dart:1021:19)
E/flutter (12041): #15     _CustomZone.bindCallback.<anonymous closure>  (dart:async/zone.dart:947:23)
E/flutter (12041): #16     Timer._createTimer.<anonymous closure>  (dart:async-patch/timer_patch.dart:21:15)
E/flutter (12041): #17     _Timer._runTimers  (dart:isolate-patch/timer_impl.dart:382:19)
E/flutter (12041): #18     _Timer._handleMessage  (dart:isolate-patch/timer_impl.dart:416:5)
E/flutter (12041): #19     _RawReceivePortImpl._handleMessage  (dart:isolate-patch/isolate_patch.dart:172:12)

我非常积极地获取图像或将其传递给firebase的方式是问题,但我尝试了无数方法,但似乎没有任何效果。

4

1 回答 1

0

确保您使用的是firebase 存储而不是 firebase 数据库来存储图像。看到这个答案。一旦你有了一个实例 firebase 存储和一个存储引用,它应该就像在该引用上调用一个方法一样简单。

编辑:这是一些未经测试的代码,显示了一种方式。

import 'package:approachbuilder/models/profile.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as path;

final FirebaseStorage firebaseStorage = FirebaseStorage();
final StorageReference storageReference = firebaseStorage.ref();

class UserProfileImage extends StatelessWidget {
  UserProfileImage(this.userDocument);

  /// The current user's profile document in firebase
  /// gotten through Firestore.instance.collection('users).document(userId);
  final DocumentReference userDocument;

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<Profile>(
      // Unnecessary step, maps the raw profile into a class intance
      // that uses a JsonSerializable and FunctionalData model
      stream: userDocument
          .snapshots()
          .map((snapshot) => Profile.fromJson(snapshot.data)),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return CircularProgressIndicator();

        return GestureDetector(
          onTap: () => _getAndSetImage(snapshot.data),
          // Traditional NetworkImage doesn't handle errors that well
          child: CachedNetworkImage(
            imageUrl: snapshot.data.photoUrl,
            placeholder: (context, url) => CircularProgressIndicator(),
            errorWidget: (context, url, error) => Icon(Icons.error),
          ),
        );
      },
    );
  }

  void _getAndSetImage(Profile profile) async {
    final imageFile = await ImagePicker.pickImage(source: ImageSource.camera);

    if (imageFile == null) return;

    final baseImageFileName = path.basename(imageFile.path);
    final imageRef = storageReference.child(baseImageFileName);
    final uploadTask = imageRef.putFile(imageFile);

    await uploadTask.onComplete.then((snapshot) async {
      // File has been successfully added to firebase storage
      final downloadUrl = await snapshot.ref.getDownloadURL();

      // Remove previous photoUrl from fb storage if there is one
      await deleteFirebaseResource(profile.photoUrl);

      await userDocument.setData(
        profile.copyWith(photoUrl: downloadUrl).toJson(),
      );
    });
  }

  Future<void> deleteFirebaseResource(String url) async {
    StorageReference storageRef =
        await firebaseStorage.getReferenceFromUrl(url);

    if (storageRef == null) return;

    await storageRef.delete();
  }
}

于 2019-10-29T14:29:44.240 回答