gpt4 book ai didi

firebase - 无法将Firebase存储镜像的网址添加到实时数据库

转载 作者:行者123 更新时间:2023-12-03 04:59:26 25 4
gpt4 key购买 nike

在此应用程序中,我可以通过相机单击图片或从图库中上传图片,然后将其传递给提供者。我想将该图像上传到Firebase Storage,然后将其Image Url与其他一些String和double类型信息一起存储在实时数据库中。但是我似乎无法做到这一点,因为在处理图像URL之前,数据似乎已上传到实时数据库中。图像仍正确上传到存储中。
这是我的Provider类的代码。

有关的方法是uploadPic()和addPlace()

import 'dart:io';
import 'dart:convert';
import 'package:path/path.dart' as Path;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:firebase_storage/firebase_storage.dart';
import '../models/place.dart';

class MyPlaces with ChangeNotifier {

List<Place> _places = [];

List<Place> get places {
return [..._places];
}

Future<void> fetchAndSetPlaces() async {
const url = 'my firebase url';
try {
final response = await http.get(url);
final extractedData = json.decode(response.body) as Map<String,dynamic>;
final List<Place> loadedPlaces = [];
extractedData.forEach((id, data) {
loadedPlaces.add(Place(
id: id,
cropName: data['cropName'],
imageUrl: data['imageUrl'],
location: Location(
latitude: data['latitude'],
longitude: data['longitude'],
//address: data['address'],
),
));
_places = loadedPlaces;
notifyListeners();
});
} catch(error) {
throw error;
}
}

Future<void> addPlace(String cropName, File image, Location loc) async {
const url = 'my firebase url';
String imageUrl;
await uploadPic(image, imageUrl);
try {
final response = await http.post(url, body: json.encode({
'cropName' : cropName,
'imageUrl' : imageUrl,
'latitude' : loc.latitude,
'longitude' : loc.longitude,
}));
final newPlace = Place(
id: json.decode(response.body)['name'],
cropName: cropName,
imageUrl: imageUrl,
location: loc,
);
_places.add(newPlace);
notifyListeners();
} catch (error) {
throw error;
}


}

Place findPlaceById(String id) {
return _places.firstWhere((place) => place.id == id);
}

Future uploadPic(pickedImage, imageUrl) async {
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child('chats/${Path.basename(pickedImage.path)}}');
StorageUploadTask uploadTask = firebaseStorageRef.putFile(pickedImage);
await uploadTask.onComplete;
print("File uploaded!");
firebaseStorageRef.getDownloadURL().then((fileUrl) {
imageUrl = fileUrl;
});
notifyListeners();
}

}

我在SubmitForm()方法的表单页面中调用addplace()方法。
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../models/place.dart';
import '../providers/my_places.dart';
import '../widgets/image_input.dart';
import '../widgets/location_input.dart';
import '../widgets/custom_drawer.dart';
import '../screens/my_geo_tags_screen.dart';

class AddNewPlaceScreen extends StatefulWidget {

static const routeName = '/add_new_place_screen';

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

class _AddNewPlaceScreenState extends State<AddNewPlaceScreen> {

Place currentPlace;

final _cropNameController = TextEditingController();
File _pickedImage;
Location _pickedLocation;

void selectImage(File image) {
setState(() {
_pickedImage = image;
});
}

void selectLocation(double lat, double long) {
_pickedLocation = Location(
latitude: lat,
longitude: long,
);
}



void _submitForm() {
if (_cropNameController.text == null || _pickedImage == null || _pickedLocation == null) {
return;
}
Provider.of<MyPlaces>(context).addPlace(_cropNameController.text, _pickedImage, _pickedLocation);
Navigator.of(context).pop();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Add new Geo Tag", style: Theme.of(context).textTheme.title),
iconTheme: IconThemeData(color: Colors.amber),
),
drawer: CustomDrawer(),
body: SingleChildScrollView(
child: Container(
padding: EdgeInsets.all(20),
child: Column(
children: <Widget>[
TextField(
style: TextStyle(
color: Theme.of(context).primaryColor,
),
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
),
labelText: "Name of the crop",
labelStyle: TextStyle(
color: Theme.of(context).primaryColor,
),
),
controller: _cropNameController,
),
SizedBox(height: 15),
ImageInput(selectImage),
SizedBox(height: 15),
LocationInput(selectLocation),
],
),
),
),
floatingActionButton: FloatingActionButton(
backgroundColor: Theme.of(context).accentColor,
child: Icon(
Icons.save,
color: Theme.of(context).primaryColor,
),
onPressed: () {
_submitForm();
Navigator.of(context).pushReplacementNamed(MyGeoTagsScreen.routeName);
},
),
);
}
}

最佳答案

我认为您需要等待firebaseStorageRef.getDownloadURL().then((fileUrl) {中的Future uploadPic。我相信,将await和.then混合使用可能会导致问题。因此,尝试删除.then,然后简单地执行以下语句imageUrl = await firebaseStorageRef.getDownloadURL();

关于firebase - 无法将Firebase存储镜像的网址添加到实时数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59905748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com