Select an Image
Use the image_picker package to select an image.
Future<void> imgFromGallery() async {
final pickedFile = await ImagePicker().pickImage(source: ImageSource.gallery);
Uint8List imageData = await XFile(pickedFile!.path).readAsBytes();
uploadImage(imageData );
}
Upload to Cloud Storage
Use the UUID package to create a unique name.
Future<String> uploadImage(Uint8List xfile) async {
Reference ref = _storage.ref().child('Folder');
String id = const Uuid().v1();
ref = ref.child(id);
UploadTask uploadTask = ref.putData(
xfile,
SettableMetadata(contentType: 'image/png'),
);
TaskSnapshot snapshot = await uploadTask;
String downloadUrl = await snapshot.ref.getDownloadURL();
return downloadUrl;
}
Upload to Cloud Firestore
Future<void> addData() async {
try {
await FirebaseFirestore.instance.('DBname').add({'image':downloadUrl});
} on FirebaseException catch (e) {
} catch (_) {
}
}
Show image in the flutter Web App
- Open the Google cloud console, select your project and start a cloud terminal session by clicking the
>_
icon button in the top navbar.
- Click the open editor button, then create the cors.json file and enter the code below and save it.
[
{
"origin": ["*"],
"method": ["GET"],
"maxAgeSeconds": 3600
}
]
- Open Terminal (Cloud Shell) and run the below code.
gsutil cors set cors.json gs://your-bucket
Note: replace your bucket id from firebase Storage
- Now make the Ui in the Flutter Web App
Image.network(widget.project.image!)
Note: Only if you have already set the following codes
web/index.html
<HTML>
....
<body>
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js";
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-storage.js";
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-firestore.js";
const firebaseConfig = {
apiKey: "....",
authDomain: "...",
projected: "....",
storageBucket: "...",
messagingSenderId: "....",
appId: "....",
measurementId: "...."
};
const app = initializeApp(firebaseConfig);
</script>
....
</body>
</html>
firebase-dart
: github.com/FirebaseExtended/firebase-dart/tree/master/example/… – Trichloride