将多张图片上传到 Firestore 时出错

时间:2020-12-29 13:14:44

标签: flutter flutter-image

我在使此代码正常工作时遇到问题。我反复查看了代码中的错误,但我没有发现任何错误。我的猜测是问题可能出在我的互联网连接上,但我想加倍确定。

有人可以帮我检查我的代码吗,很可能我做错了什么。

首先,在正文部分,应该显示用户的个人资料图片。它显示一个错误(“profilePic was called on null”)。我不知道为什么;

leading: CircleAvatar(
           backgroundImage:
               CachedNetworkImageProvider(widget.user.profilePic),
         ),

此外,当我尝试上传多张图片时,只会上传第一张图片,并且不会在 Cloud Firestore 中自动创建集合。

请参阅下面的完整代码。我真的很感激这里有人的帮助;

final postsReference = FirebaseFirestore.instance.collection("posts");
final StorageReference storageReference =
    FirebaseStorage.instance.ref().child("Uploads");

class PhotoUpload extends StatefulWidget {
  final z.User user;

  PhotoUpload({this.user});

  @override
  _PhotoUploadState createState() => _PhotoUploadState();
}

class _PhotoUploadState extends State<PhotoUpload>
    with AutomaticKeepAliveClientMixin<PhotoUpload> {


  List<File> _image = [];
  final picker = ImagePicker();
  String postId = Uuid().v4();
  bool uploading = false;
  TextEditingController descriptionTextEditingController =
      TextEditingController();
  TextEditingController locationTextEditingController = TextEditingController();

  bool get wantKeepAlive => true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.purple,
        onPressed: () => controlImageUpload(),
        child: Icon(
          Icons.send,
          size: 32,
          color: Colors.white,
        ),
      ),
      appBar: AppBar(
        backgroundColor: Colors.purple,
        centerTitle: true,
        title: Text(
          "Image Upload",
          style: TextStyle(
              fontSize: 20.0, color: Colors.white, fontWeight: FontWeight.bold),
        ),
      ),
      body: Column(
        children: <Widget>[
          uploading ? linearProgress() : Text(""),
          Expanded(
            child: GridView.builder(
                itemCount: _image.length + 1,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3),
                itemBuilder: (context, index) {
                  return index == 0
                      ? Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                              IconButton(
                                icon: Icon(Icons.camera_alt,
                                    color: Colors.purple, size: 40.0),
                                onPressed: () =>
                                    !uploading ? captureImage(context) : null,
                              ),
                              Padding(
                                padding: const EdgeInsets.all(2.0),
                                child: RaisedButton(
                                  shape: RoundedRectangleBorder(
                                      borderRadius:
                                          BorderRadius.circular(35.0)),
                                  child: Text(
                                    "Load Image",
                                    style: TextStyle(
                                        color: Colors.white, fontSize: 14.0),
                                  ),
                                  color: Colors.purple,
                                  onPressed: () => captureImage(context),
                                ),
                              ),
                            ])
                      : Container(
                          margin: EdgeInsets.all(3),
                          decoration: BoxDecoration(
                              image: DecorationImage(
                                  image: FileImage(_image[index - 1]),
                                  fit: BoxFit.cover)),
                        );
                }),
          ),
          ListTile(
            leading: CircleAvatar(
               backgroundImage:
                   CachedNetworkImageProvider(widget.user.profilePic),
             ),
            title: Container(
              width: 250.0,
              child: TextField(
                style: TextStyle(color: Colors.black),
                controller: descriptionTextEditingController,
                decoration: InputDecoration(
                  hintText: "Say something!",
                  hintStyle: TextStyle(color: Colors.grey),
                  border: InputBorder.none,
                ),
              ),
            ),
          ),
          Divider(),
          ListTile(
            leading: Icon(
              Icons.person_pin_circle,
              color: Colors.purple,
              size: 36,
            ),
            title: Container(
              width: 250.0,
              child: TextField(
                style: TextStyle(color: Colors.black),
                controller: locationTextEditingController,
                decoration: InputDecoration(
                  hintText: "Add location",
                  hintStyle: TextStyle(color: Colors.grey),
                  border: InputBorder.none,
                ),
              ),
            ),
          ),
          Container(
            width: 220,
            height: 50,
            alignment: Alignment.center,
            child: RaisedButton.icon(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(35)),
              color: Colors.purple,
              icon: Icon(
                Icons.location_on,
                color: Colors.white,
              ),
              label: Text(
                "Get my location",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: getUserCurrentLocation,
            ),
          ),
          
        ],
      ),
    );
  }


  upLoadImageFromGallery() async {
    final pickedFile = await picker.getImage(source: ImageSource.gallery);

    setState(() {
      _image.add(File(pickedFile?.path));
    });
    if (pickedFile.path == null) {
      retrieveLostData();
    }
  }

  captureImageWithCamera() async {
    final pickedFile = await picker.getImage(source: ImageSource.camera);

    setState(() {
      _image.add(File(pickedFile?.path));
    });
    if (pickedFile.path == null) {
      retrieveLostData();
    }
  }

  captureImage(mContext) {
    return showDialog(
        context: mContext,
        builder: (context) {
          return SimpleDialog(
            title: Text("New Upload",
                style:
                    TextStyle(color: Colors.grey, fontWeight: FontWeight.bold)),
            children: <Widget>[
              SimpleDialogOption(
                child: Text("Capture with Camera",
                    style: TextStyle(color: Colors.grey)),
                onPressed: captureImageWithCamera,
              ),
              SimpleDialogOption(
                child: Text("Select from Gallery",
                    style: TextStyle(color: Colors.grey)),
                onPressed: upLoadImageFromGallery,
              ),
              SimpleDialogOption(
                child: Text("Done", style: TextStyle(color: Colors.grey)),
                onPressed: () => Navigator.pop(context),
              ),
            ],
          );
        });
  }

  Future<void> retrieveLostData() async {
    final LostData response = await picker.getLostData();
    if (response.isEmpty) {
      return;
    }
    if (response.file != null) {
      setState(() {
        _image.add(File(response.file.path));
      });
    } else {
      print(response.file);
    }
  }

  Future<String> uploadPhoto() async {
    for (var img in _image) {
      StorageUploadTask mStorageUploadTask = storageReference
          .child('images/${Path.basename(img.path)}')
          .putFile(img);
      StorageTaskSnapshot storageTaskSnapshot =
          await mStorageUploadTask.onComplete;
      String downloadUrl = await storageTaskSnapshot.ref.getDownloadURL();

      return downloadUrl;
    }
  }

  
  getUserCurrentLocation() async {
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    List<Placemark> placeMarks =
        await placemarkFromCoordinates(position.latitude, position.longitude);
    Placemark mPlaceMark = placeMarks[0];
    String completeAddressInfo =
        '${mPlaceMark.subThoroughfare} ${mPlaceMark.thoroughfare}, ${mPlaceMark.subLocality} ${mPlaceMark.locality}, ${mPlaceMark.subAdministrativeArea} ${mPlaceMark.administrativeArea}, ${mPlaceMark.postalCode} ${mPlaceMark.country},';
    String cityStateCountry =
        '${mPlaceMark.subLocality}, ${mPlaceMark.locality}, ${mPlaceMark.country}';
    locationTextEditingController.text = cityStateCountry;
  }

  saveImageInfoToFireStore({String url, String location, String description}) {
    postsReference
        .doc(widget.user.id)
        .collection("postImages")
        .doc(postId)
        .set({
      "postId": postId,
      "ownerId": widget.user.id,
      "timestamp": timestamp,
      "likes": {},
      "dislikes": {},
      "username": widget.user.username,
      "description": description,
      "location": location,
      "url": url,
    });
  }

  controlImageUpload() async {
    setState(() {
      uploading = true;
    });

    String downloadUrl = await uploadPhoto();

    saveImageInfoToFireStore(
        url: downloadUrl,
        location: locationTextEditingController.text,
        description: descriptionTextEditingController.text);

    locationTextEditingController.clear();
    descriptionTextEditingController.clear();

    setState(() {
      _image = [];
      uploading = false;
      postId = Uuid().v4();
    });
  }
}

0 个答案:

没有答案