firebase - 无法将 Firebase 存储映像的 Url 添加到实时数据库
问题描述
在这个应用程序中,我通过相机单击图片或从图库上传图片并将其传递给提供商。我想将该图像上传到 Firebase 存储,然后将其图像 URL 与其他一些字符串和双精度类型信息一起存储在实时数据库中。但我似乎无法这样做,因为数据似乎在处理图像 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();
推荐阅读
- javascript - 单击datalist中的选项值时如何更改占位符文本
- dependencies - 修复依赖解析错误
- xamarin - Xamarin.Build.Download.targets - 无效的 ID
- laravel - Laravel 将值从查询传递到 with() 函数
- mysql - MySQL 在安装过程中无法创建“my-template.ini”文件
- ios - 切片时返回错误索引值的数据类型
- android - React-Native 错误 - com.facebook.react.common.JavascriptException: TypeError: undefined is not an object (evalating 't.apply')
- html - Flutter:获取 HTML TAG 的某些元素
- javascript - JavaScript 为什么单 $ 和双 $$ 的字符串插值在替换函数中具有相同的结果?
- reactjs - 执行突变时 Apollo 客户端错误