flutter firestore image: How to display image through url which is in firebase firestore?

Viewed 719

I am getting the images url in console and it is printing in it, but I am not able to display the image inside the container. This is the complete code with Dot indicators and delete button. This code works fine as I'm able to display the image if I get them direct through cloud storage but not able to get it through firestore which is stored in image collection in array with index uploaded as map. But url gets print in console as I have mentioned in code below. pls check it out. PS: second and third page may or may be not related here with query but it might help someone who are trying to get dot indicators or delete button or full image view as this code works fine if I get the images direct through cloud storage.Thanks for your time.enter image description here

   class PortfolioGallarySubPageTWO extends StatefulWidget{


 int currentIndex;
 List<String> imageList;


 PortfolioGallarySubPageTWO({Key key,@required this.imageList,@required this.currentIndex})
  :super(key:key);

 @override
 _PortfolioGallarySubPageTWO createState() => _PortfolioGallarySubPageTWO();
  }

 class _PortfolioGallarySubPageTWO extends State<PortfolioGallarySubPageTWO>
  with SingleTickerProviderStateMixin {


 final GlobalKey<FormState> formKey = new GlobalKey<FormState>();
 final GlobalKey<ScaffoldState> key = new GlobalKey<ScaffoldState>();

 final _stoarge = FirebaseStorage.instance;
 final CollectionReference _reference = FirebaseFirestore.instance.collection(
  "users");
 final auth = FirebaseAuth.instance;

 final FirebaseFirestore fb = FirebaseFirestore.instance;


 List<File> _images = [];
 List<String> imageList = [];
 int currentIndex;



  @override
 void initState() {
   super.initState();
  _getImagesOK();
  
  }

   @override
   void dispose() {
    super.dispose();
   }


    @override
   Widget build(BuildContext context) {
    return Scaffold(
      key: key,
    extendBodyBehindAppBar: true,
    appBar: AppBar(
      elevation: 0,
      backgroundColor: Colors.transparent,
       actions: [
         ElevatedButton(
           child: Text("DONE", style: TextStyle(fontSize: 15)),
           onPressed: () {
          _uploadImages();
        },
        style: ElevatedButton.styleFrom(
            padding: EdgeInsets.fromLTRB(25.0, 15.0, 25.0, 10.0),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(30.0))),
      ),
    ],
  ),
  body: Container(
    width: _maxScreenWidth,
    child: SafeArea(
      child: Form(
        key: formKey,
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [

              
              Container(

                height: 160.0,
                padding: EdgeInsets.symmetric(vertical: 15.0,horizontal: 15.0),

                child: CustomScrollView(
                 
                  physics: const BouncingScrollPhysics(),


                  slivers: <Widget>[
                    SliverPadding(

                      padding: const EdgeInsets.all(10),
                      sliver:
                      _buildContentTWO(imageList),

                    )
                  ],
                ),
              ),


            ],
          ),
        ),
      ),
    ),
  ),
);
   }



    _getImagesOK() async {
    DocumentSnapshot firebaseDoc = await FirebaseFirestore.instance.collection(
      "users").doc(auth.currentUser.uid).get();

     List imageList = firebaseDoc.data()['images'];

     print(imageList[0]);

     String _u = await imageList.toString();


    imageList.add(_u);
    setState(() {
      print(imageList.length);
     print(imageList);
      });
    }


    SliverGrid _buildContentTWO(List<String> imageList) {
    return SliverGrid(

      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
    maxCrossAxisExtent: 150,
    mainAxisSpacing: 10,
    crossAxisSpacing: 10,
  ),
  delegate: SliverChildBuilderDelegate(

        (BuildContext context, int index) {
      return PortfolioGalleryImageWidgetTWO(imageList: imageList[index],
        onImageTap: () =>
            Navigator.push(context,
              _createGalleryDetail(imageList, index),
            ),
      );
    },
    childCount: imageList.length,
  ),

);
 }

    MaterialPageRoute _createGalleryDetail(List<String> imageList, int index) {
   return MaterialPageRoute(builder: (context) =>
      PortfolioGalleryDetailPageTWO(
        imageList: imageList,
         currentIndex: index,
        ),
    );
  }

}

The second page: The page is for DOT indicators and to get index and displayed on image

   class PortfolioGalleryDetailPageTWO extends StatefulWidget{
   final List<String> imageList;
   final int currentIndex;

   PortfolioGalleryDetailPageTWO({Key key, @required this.imageList,@required this.currentIndex})
  : super(key: key);

   @override
  _PortfolioGalleryDetailPageTWO createState() => _PortfolioGalleryDetailPageTWO();
}

   class _PortfolioGalleryDetailPageTWO extends State<PortfolioGalleryDetailPageTWO>{
    int _currentIndex;
   PageController _pageController;

    @override
    void initState(){
   super.initState();
    _currentIndex = widget.currentIndex;
   _pageController = PageController(initialPage: _currentIndex);
    }

   final auth = FirebaseAuth.instance;

   @override
   Widget build (BuildContext context){

return Scaffold(
  backgroundColor: Colors.black,
  appBar: AppBar(backgroundColor: Colors.black,),
  body: _buildContent(),
);
  }

  Widget _buildContent(){

return Stack(
  children: [
    _buildPhotoViewGallery(),
    _buildIndicator(),
    _deleteImage(),
  ],
);
 }

   Widget _deleteImage(){
   return Positioned(
     right: -2,
   top: -9,
  child: new Deletebtn(),
);
   }



     Widget _buildIndicator(){
    return Positioned(
    bottom: 2.0,
  left: 2.0,
  right: 2.0,
  // child: _buildDot(),
  child: _buildDottedIndicator(),
);
  }

  Row _buildDottedIndicator(){
  return Row(
  mainAxisAlignment: MainAxisAlignment.center,
  children: widget.imageList.map<Widget>((String imageList) => _buildDot(imageList)).toList(),
);
  }

  Container _buildDot(String imageList){
return Container(

  width: 5,
  height: 5,
  margin: EdgeInsets.symmetric(vertical: 10.0,horizontal: 2.0),
  decoration: new BoxDecoration(
      color: _currentIndex == widget.imageList.indexOf(imageList) ? Colors.red : Colors.white,

      borderRadius: new BorderRadius.circular(2.5),
      boxShadow: [
        new BoxShadow(
            color: Colors.red,
            blurRadius: 10.0,
            spreadRadius: 0.0,
            offset: const Offset(0.0, 1.0))
      ]),

);
  }


  PhotoViewGallery _buildPhotoViewGallery(){
  return PhotoViewGallery.builder(
  itemCount: widget.imageList.length,
  builder: (BuildContext context,int index){
    return PhotoViewGalleryPageOptions(
      imageProvider: NetworkImage(widget.imageList[index]),
      minScale: PhotoViewComputedScale.contained * 0.8,
      maxScale: PhotoViewComputedScale.covered * 1.8,
    );
  },
  scrollPhysics: const BouncingScrollPhysics(),
  pageController: _pageController,
  onPageChanged: (int index){
    setState(() {
      _currentIndex = index;
    });
  },
  scrollDirection: Axis.horizontal,
);
  }



    }

 class Deletebtn extends StatelessWidget{
 final auth = FirebaseAuth.instance;

  @override
 Widget build(BuildContext context ) {
return new Padding(padding: const EdgeInsets.all(10.0),
  child: IconButton(
    icon: Icon(Icons.delete_forever_outlined,
      color: const Color(0xFF227770),
      size: 35,
    ),
    onPressed: () async {
      var val =[];

      var userCollection = FirebaseFirestore.instance.collection("users").doc(auth.currentUser.uid).update({ "images" : FieldValue.arrayRemove(val)}).then((_) {
        print("deleted");
      });
    },
  ),
);
  }


 }

The third page: This is for the how image look inside the container and on image tap it gives full screen image view.

class PortfolioGalleryImageWidgetTWO extends StatelessWidget{
final String imageList;
final VoidCallback onImageTap;

const PortfolioGalleryImageWidgetTWO({Key key,@required this.imageList, @required this.onImageTap})
  :super(key: key);

 @override
 Widget build(BuildContext context) {
return Container(
  decoration:BoxDecoration(
    boxShadow:[
      BoxShadow(
        color: Colors.black,
        offset: Offset(2, 2),
        spreadRadius: 2,
        blurRadius: 5,
      ),
    ],
    borderRadius: BorderRadius.all(Radius.circular(10)),

  ),
  child: ClipRRect(
    borderRadius:BorderRadius.all(Radius.circular(10)),
    child: Material(
      color: Colors.transparent,
      child: Ink.image(image: NetworkImage(imageList),
        fit: BoxFit.cover,
        child: InkWell(onTap: onImageTap),
      ),
    ),
  ),
);
  }

} 
1 Answers

Try this first:

  _getImagesOK() async {
    DocumentSnapshot firebaseDoc = await FirebaseFirestore.instance.collection(
      "users").doc(auth.currentUser.uid).get();
    List<String> imageListTemp =[];
     for(var item in firebaseDoc.data()['images']){
      imageListTemp.add(item); 
     }
   
    setState(() {
      imageList=imageListTemp;
      print(imageList.length);
     print(imageList);
      });
    }
Related