【问题标题】:why sometime the imageUrl get saved inside cloud firestore database & sometime it does not get saved为什么有时图像 URL 会保存在云 Firestore 数据库中,有时却没有保存
【发布时间】:2020-06-22 19:37:29
【问题描述】:

我正在创建一个 Flutter 应用程序,它将 Image-url 存储在 Cloud Firestore 数据库中,并且该 url 以图像的形式获取并显示在我的 Flutter 应用程序中。问题在于 image-url 有时它被保存在数据库中,有时它没有。当它被保存时,获取过程正常工作,当它没有保存或未保存时,它将返回一个错误值,其中显示了如图所示的 null msg。

我不知道为什么会发生这种情况,有时数据会被保存,有时却未保存。

请参阅以下代码以将图像保存在云 Firestore 数据库中。

import 'package:intl/intl.dart';
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mi_card/duplicate.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mi_card/widget/provider_widget.dart';
import 'package:path/path.dart' as path;
import 'package:firebase_storage/firebase_storage.dart';
import '../sec.dart';


class  EditProductScreen extends StatefulWidget {
  @override
  _EditProductScreenState createState() => _EditProductScreenState();
}


class _EditProductScreenState extends State<EditProductScreen> {

  //for selecting picture from galary of phone
  var sampleImage;
  Future captureImage() async {
    var tempImage = await ImagePicker.pickImage(source: ImageSource.camera);

    setState(() {
      sampleImage = tempImage;
    });
    String fileName = path.basename(sampleImage.path);
    final StorageReference firebaseStorageRef =
    FirebaseStorage.instance.ref().child('entry/student entry/'+fileName);
    final StorageUploadTask task =
    firebaseStorageRef.putFile(sampleImage);

    var ImageUrl= await(await task.onComplete).ref.getDownloadURL();
    url=ImageUrl.toString();
    print("Image Url="+url);
    //saveToDatabase(url);

  }

  void saveToDatabase(url){

  }

  //for camera opening and capturing the picture
  Future getImage() async {
    var tempImage = await ImagePicker.pickImage(source: ImageSource.gallery);

    setState(() {
      sampleImage = tempImage;
    });
    String fileName = path.basename(sampleImage.path);
    final StorageReference firebaseStorageRef =
    FirebaseStorage.instance.ref().child('entry/student entry/'+fileName);
    final StorageUploadTask task =
    firebaseStorageRef.putFile(sampleImage);

    var ImageUrl= await(await task.onComplete).ref.getDownloadURL();
    url=ImageUrl.toString();
    print("Image Url="+url);
    saveToDatabase(url);
  }
  final _priceFocusNode = FocusNode();
  final _formKey = GlobalKey<FormState>();
  final _firestore = Firestore.instance;
  String url;
  





  var _initValues = {
    'title': '',
    'description': '',
    'price': '',
    'imageUrl': '',
  };
  var _isInit = true;




  @override
  void didChangeDependencies() {
    if (_isInit) {
      final productId = ModalRoute.of(context).settings.arguments as String;

    }
    _isInit = false;
    super.didChangeDependencies();
  }

  @override
  void dispose() {

    _priceFocusNode.dispose();

    super.dispose();
  }



  void _saveForm() async{

    final isValid = _formKey.currentState.validate();
    if (!isValid) {
      return;
    }
    _formKey.currentState.save();


    var dbTimeKey = new DateTime.now();
    var formatDate=new DateFormat('dd/MMMM/yyyy');
    var formatTime=new DateFormat('dd/MMMM/yyyy &'' hh:mm aaa, EEEE');


    String date = formatDate.format(dbTimeKey);
    String time = formatTime.format(dbTimeKey);



    final uid = await Provider.of(context).auth.getCurrentUID();


    // collection reference for every  user
    DocumentReference Collection =  Firestore.instance.collection(' entry').document();
    Collection.setData({
      "Entry-time": time,
      'image': url,
    });


    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => MyApp()),
    );
  }

  List<String> _locations = ['NA','1st year', '2 year', '3 year', '4 year']; // Option 2
  String _selectedLocation;
  @override
  Widget build(BuildContext context) {

    var _blankFocusNode = new FocusNode();

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        title: Text('ENTRY'),
        centerTitle: true,
        leading: new
        IconButton(
          icon: Icon(Icons.arrow_back),
          color: Colors.white,
          onPressed: () {
            Navigator.pop(
              context,
              MaterialPageRoute(builder: (context) => SecondRoute()),
            );
          },
        ),
        actions: <Widget>[
          FlatButton(
            textColor: Colors.white,
            onPressed: _saveForm,
            child: Text("Save",),
          ),

        ],

      ),
      backgroundColor: Colors.blueAccent,
      body: GestureDetector (
        onTap: () {
          FocusScope.of(context).requestFocus(_blankFocusNode);
        },
        child: Form(
          key: _formKey,
          child: ListView(
            scrollDirection: Axis.vertical,
            children: <Widget>[
              SizedBox(
                height: 20.0,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Align(
                    alignment: Alignment.center,
                    child: CircleAvatar(
                      radius:73 ,
                      backgroundColor: Colors.white,
                      child: ClipOval(
                        child: new SizedBox(
                          width: 125,
                          height:125,
                          child: sampleImage != null
                              ? Image.file(
                            sampleImage,
                            height: 108,
                            fit: BoxFit.fill,
                          )
                              : IconButton(
                            icon: Icon(
                              Icons.person,
                              color: Colors.grey[400],
                            ),
                            iconSize: 80.0,
                            //onPressed:_takePicture
                          ),
                        ),
                      ),

                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 0.0),
                    child: IconButton(

                      icon: Icon(
                        Icons.camera_alt,
                        color: Colors.black,
                        size: 30.0,
                      ),
                      onPressed: captureImage,
                    ),

                  ),

                  Padding(
                    padding: EdgeInsets.only(top: 00.0),
                    child: IconButton(
                      icon: Icon(
                        Icons.folder,
                        color: Colors.orangeAccent[100],
                        size: 30.0,
                      ),
                      onPressed: getImage,
                    ),

                  ),
                ],

              ),

],
          ),
        ),
      ),

    );
  }
}

如何处理这个错误?

【问题讨论】:

  • 即使您无法显示图像,您的图像是否保存在 Firebase 存储中?我认为您的代码可能处于竞争状态,@griffins 的回答可以解决这个问题跨度>

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

这是一种将图像上传到存储并返回 url 的更好方法

          final StorageReference storageReference =
                          FirebaseStorage().ref().child("path/$name");
        
                      final StorageUploadTask uploadTask =
                          storageReference.putFile(imaeFile);
        
                      final StreamSubscription<StorageTaskEvent> streamSubscription =
                          uploadTask.events.listen((event) {
                        // You can use this to notify yourself or your user in any kind of way.
                        // For example: you could use the uploadTask.events stream in a StreamBuilder instead
                        // to show your user what the current status is. In that case, you would not need to cancel any
                        // subscription as StreamBuilder handles this automatically.
       print('EVENT ${event.type}');
                  });
    
    // Cancel your subscription when done.
                  await uploadTask.onComplete;
                  streamSubscription.cancel();
                  String url =
                      await (await uploadTask.onComplete).ref.getDownloadURL();
saveToDatabase(url);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    相关资源
    最近更新 更多