简体   繁体   English

Flutter: Firebase 存储不上传多张图片,总是重复相同的路径?

[英]Flutter: Firebase Storage is not uploading multiple images, it always repeat the same path?

class CategoryScreen extends StatefulWidget {
  static const routeName = '/category-screen';
  @override
  _CategoryScreenState createState() => _CategoryScreenState();
}

class _CategoryScreenState extends State<CategoryScreen> {
  @override
  Widget build(BuildContext context) {
    //from co_detai_screen.dart
    final companyId = ModalRoute.of(context).settings.arguments as String;
    //
    final _form = GlobalKey<FormState>();
    String _car = '';
    String _carModel = '';
    File carImage;
    
    String ranDom = randomBetween(0, 300).toString();
    
    void _submitCarCategory() async{
    final isValid = _form.currentState.validate();
    
    if(isValid){
      _form.currentState.save();
       //.... upload image here
/*===============================Here is firebase storage work==============================*/
      final ref = FirebaseStorage.instance.ref().child('cars').child(ranDom + '.jpg');
      await ref.putFile(carImage);
      //kan fe .onComplete ba3ed (image)**strong text**
      //.... upload image here

      //... now want to get this image into the firestore
      final url = await ref.getDownloadURL();
      //... now want to get this image into the firestore
      FirebaseFirestore.instance.collection('companies').doc(companyId).collection('category').doc().set(({
        'carName': _car,
        'carModel': _carModel,
        'car_image': url
      }));
      Navigator.of(context).pop();
    }
  }


    void _pickedImage(File image){
      carImage = image;
    }

    void _showDialog(){
      showDialog(context: context, builder: (context)=> AlertDialog(
        title: Text('Add Category'),
        content: SingleChildScrollView(
          child: Form(
          key: _form,
                child: Container(
                height: 450,
                width: double.infinity,
                padding: EdgeInsets.all(20),
                  
                      child: Column(
                      children: [
                        Text('Add Category', style: TextStyle(fontSize: 16),),
                        SizedBox(height: 10,),
                        UserImagePicker(_pickedImage),
                        TextFormField(decoration: InputDecoration(labelText: 'Car'),
                         onSaved: (value){
                            _car = value;
                          },
                        ),
                        TextFormField(
                          decoration: InputDecoration(labelText: 'Car model'),
                          onSaved: (value){
                            _carModel = value;
                          },
                        ),
                        SizedBox(height: 20,),
                        FlatButton(
                          onPressed: (){
                            _submitCarCategory();
                          }, 
                          child: Text('Add'),
                          color: Colors.indigo,
                          textColor: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20)
                          ),
                          ),
                      ],
                  ),
                    ),
                    ),
    ),
      ),
      );
    }


    return FutureBuilder(
      future: FirebaseFirestore.instance.collection('companies').doc(companyId).get(),
      builder: (ctx, futureSnapshot){
        if(futureSnapshot.hasData){
          return Scaffold(
            appBar: AppBar(title: Row(
              children: [
                Text(futureSnapshot.data['coname']),
                SizedBox(width: 5,),
                Text('Category'),
              ],
            ),
            ),
            body: Column(
                children: [
                  SizedBox(height: 30,),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(left: 15.0),
                        child: FlatButton(
                          onPressed: ()=> _showDialog(), 
                          child: Text('Add Category'),
                          color: Colors.indigo,
                          textColor: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20)
                          ),
                        ),
                      ),
                  ],
                  ),

                  SizedBox(height: 10,),
                  Divider(),
                  SizedBox(height: 10,),
                 
                  Expanded(
                    child: CategoryWidget(
                      //futurebuilder snapshot id
                      futureSnapshot.data.id
                      ),
                  ),
                
                ],
              ),
          );
        }else{
          return Scaffold(
            body: Center(child: CircularProgressIndicator()),
          );
        }
      }
      );
  }
}

Instead of using而不是使用

 String ranDom = randomBetween(0, 300).toString();

Assign a Date and Time(including seconds) to your image name or combination of both ranDom and dateTime.为您的图像名称或随机数和日期时间的组合分配日期和时间(包括秒数)。

final ref = FirebaseStorage.instance.ref().child('cars').child(ranDom + DateTime + '.jpg');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM