我想在实时数据库中保存多个图像 url,但每次旧图像 url 替换为 flutter 中的新图像 url

时间:2021-07-13 06:23:13

标签: firebase flutter firebase-realtime-database firebase-storage flutter-dependencies

我想在实时数据库中保存多个图像 URL,但每次在 Flutter 中旧图像 URL 被新图像 URL 替换

请帮助解决这个问题。我是新手

这是我的代码:-

颤动 正如您在颤振代码中看到的,我正在尝试在 firebase 存储中上传多个图像,并将图像 url 存储在 firebase 实时数据库中

import 'dart:io';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_storage/firebase_storage.dart'; 
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as Path;

void main() async {
 WidgetsFlutterBinding.ensureInitialized();
 await Firebase.initializeApp();
 runApp(MyApp());
}

class MyApp extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
  return MaterialApp(
  home: MyHomePage(),
  );
  }
}

class MyHomePage extends StatefulWidget {
 @override
 _MyHomePageState createState() => _MyHomePageState();
 }

class _MyHomePageState extends State<MyHomePage> {
  Reference reference = FirebaseStorage.instance.ref();

  List<File> imageList = [];
  File? image;
  final picker = ImagePicker();
  int i = 0;
  final databaseRef = FirebaseDatabase.instance.reference();

Future _upload() async {
for (var img in imageList) {
  reference = FirebaseStorage.instance
      .ref()
      .child('images/${Path.basename(img.path)}');
  await reference.putFile(img).whenComplete(() async {
    reference.getDownloadURL().then((value) {
      i++;
      databaseRef.child("All Data").child("Images").set({"$i": value});
    });
  });
 }
}

@override
Widget build(BuildContext context) {
var height = MediaQuery.of(context).size.height;
var width = MediaQuery.of(context).size.width;

return Scaffold(
  appBar: AppBar(
    title: Text("Image upload in firebase flutter"),
  ),
  body: Center(
    child: Column(
      children: [
        Container(
          margin: EdgeInsets.only(left: 15, right: 15),
          height: height * 0.18,
          child: Row(
            children: [
              InkWell(
                child: Container(
                  width: width * 0.30,
                  decoration: BoxDecoration(
                      color: Colors.grey.shade100,
                      borderRadius: BorderRadius.circular(10)),
                  margin: EdgeInsets.only(right: 10),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.photo_camera,
                        color: Colors.blue.shade900,
                        size: 32,
                      ),
                      Text(
                        "Add Image",
                        style: TextStyle(
                            fontSize: 16, color: Colors.blue.shade900),
                      )
                    ],
                  ),
                ),
                onTap: () {
                  chooseImages();
                },
              ),
              imageList == null
                  ? Container()
                  : Expanded(child: imagesData(imageList))
            ],
          ),
        ),
        InkWell(
          onTap: () {
            _upload();
          },
          child: Container(
            width: 100,
            height: 50,
            color: Colors.blue,
            child: Text("Upload"),
          ),
        )
      ],
    ),
  ),
);
}

chooseImages() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
  imageList.add(File(pickedFile!.path));
});
if (pickedFile == null) retrieveLostData();
 }

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

Widget imagesData(List<File>? imageList) {
return ListView.builder(
    scrollDirection: Axis.horizontal,
    itemCount: imageList!.length,
    itemBuilder: (context, index) {
      return Container(
        width: MediaQuery.of(context).size.width * 0.30,
        height: MediaQuery.of(context).size.height * 0.17,
        margin: EdgeInsets.only(left: 2, right: 2),
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(20)),
        child: Stack(children: [
          Container(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(25),
              child: Image.file(
                imageList[index],
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height * 0.17,
                fit: BoxFit.cover,
              ),
            ),
          ),
          Positioned(
            child: InkWell(
              onTap: () {
                print("${imageList[index]}");
                setState(() {
                  imageList.remove(imageList[index]);
                });
              },
              child: Icon(
                Icons.cancel,
                color: Colors.white,
              ),
            ),
            right: 10,
            top: 10,
          )
        ]),
      );
    });
   }
 }

代码结束。

1 个答案:

答案 0 :(得分:0)

您的问题出在代码的这一部分:

 databaseRef.child("All Data").child("Images").set({"$i": value});

您总是覆盖相同的路径。尝试使用 push 而不是 set

 databaseRef.child("All Data").child("Images").push({"$i": value});