简体   繁体   中英

How to render image from Firebase without rebuilding?

I'm trying to implement profile image picking in my flutter app using Firebase Storage. I use image_picker to get the image and upload it to Firebase, get the download link and add the download link to the imgsrc field in the cloud firestore, from where I can render the NetworkImage.

Center(
          child: Stack(
            children: [
              buildImage(),
              Positioned(
                bottom: 5,
                right: 5,
                child: GestureDetector(
                    onTap: showPhotoAlertDialog,
                    child: buildEditIcon(Color(0xff407bff))),
              ),
            ],
          ),
        ),

How can I get the default Icons.person kind image for when the user has no profile image, and get the image from the database otherwise? The code I'm using right now is as follows:

Widget buildImage() {
    return CircleAvatar(
      backgroundImage: NetworkImage(loggedInUser.imgsrc ??
          'https://th.bing.com/th/id/R.945f33b643f2ceffcdae90fb57c61854?rik=XcI0SYBgSefoCA&riu=http%3a%2f%2fgetdrawings.com%2ffree-icon-bw%2fanonymous-avatar-icon-19.png&ehk=5n%2buJG66CeLQZsmhaMt8gag5rXuM3TdebAL6W35K1E4%3d&risl=&pid=ImgRaw&r=0'),
      backgroundColor: Colors.grey[350],
      radius: 100,
    );
  }

I created an Alert Dialog widget to choose whether to choose the image from camera or from the gallery.

showPhotoAlertDialog() {
    AlertDialog alert = AlertDialog(
      title: Text("Upload from"),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          TextButton(
            onPressed: () {
              imageFromCamera()
                  .then((value) => uploadFile())
                  .whenComplete(() => postSource());
              setState(() {});                               ----->
            },
            child: Text("Upload from camera"),
          ),
          TextButton(
            onPressed: () {
              imageFromGallery().then((value) => uploadFile());
              postSource();
              setState(() {});
            },
            child: Text("Upload from gallery"),
          )
        ],
      ),
    );

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }

To upload the image to storage and post the source to cloud firestore, I use the following methods:

Future uploadFile() async {
    if (file == null) return;

    final fileName = path.basename(file!.path);
    final destination = 'files/$fileName';

    task = FirebaseApi.uploadFile(destination, file!);
    setState(() {});

    if (task == null) return;

    final snapshot = await task!.whenComplete(() {});
    urlDownload = await snapshot.ref.getDownloadURL();

    print('Download-Link: $urlDownload');
  }

  postSource() async {
    FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;

    await firebaseFirestore
        .collection("users")
        .doc(user?.uid)
        .update({'imgsrc': urlDownload});
  }

The link gets uploaded properly and I'm able to get the link in my NetworkImage , but it doesn't get rendered immediately. I have to close the parent drawer and open it again to get it. I call setState(){} as well after posting the source, but it doesn't make any difference. How can I get the image without having to close and open the drawer?

Any help would be appreciated! Thanks

You also have to update image in model class or in this imgsrc also just add this line above setState in onPressed of TextButton.

loggedInUser.imgsrc = urlDownload;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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