name27 / flutter

0 stars 0 forks source link

firebase storage #114

Open name27 opened 1 year ago

name27 commented 1 year ago

image image image

main_controller.dart

import 'dart:io';

import 'package:day_34_test_firebase/controller/auth_controller.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

class MainController extends GetxController {
  final RxList images = [].obs;

  User? get user => Get.find<AuthController>().user.value;
  //Profile? get profile => Get.find<AuthController>().profile.value;

  fetchImages() async{
    var ref = FirebaseStorage.instance.ref('/images');
    var res = await ref.listAll();
    images.clear();
    for(var item in res.items){
      var url = await item.getDownloadURL();
      images.add(url);
    }
  }
  uploadImage(XFile file) {
    var ref = FirebaseStorage.instance.ref('images/${user!.uid}${file.name}');
    ref.putFile(File(file.path)).then((p0) => fetchImages());
  }
}

main_page.dart

import 'package:day_34_test_firebase/controller/main_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

class MainPage extends GetView<MainController> {
  const MainPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Obx(
        () => ListView(
          children: [
            const Text('메인페이지'),
            Row(
              children: [
                CircleAvatar(
                    radius: 40,
                    backgroundImage: controller.user!.photoURL != null
                        ? NetworkImage(controller.user!.photoURL!)
                        : null),
                Expanded(
                  child: SizedBox(
                    child: Card(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: const [Text('ㅁㅇㄹ'), Text('asdf')],
                      ),
                    ),
                  ),
                ),
              ],
            ),
            ...controller.images
                .map(
                  (element) => Image.network(element),
                )
                .toList(),
            TextButton(
                onPressed: () async {
                  var picker = ImagePicker();
                  var res = await picker.pickImage(source: ImageSource.gallery);
                  if (res != null) {
                    controller.uploadImage(res);
                  }
                },
                child: const Text('Upload'))
          ],
        ),
      )),
    );
  }
}