skip to Main Content

Problem with displaying images in ListView, have error app crash when load all images at once and pagination code i have now is not work for some reason

Basicly want to fetch images from this firebase colection and display them in ‘ListView’ with pagination to my app not crash.
Hopfuly somebody can help me fix this issue, thank you!

initSliderImages() async {
    var result = await FirebaseFirestore.instance.collection('galerytab1');
    result.snapshots().listen((data) {
      List imgs = [];
      data.docChanges.forEach((change) {
        var imageData = change.doc.data();
        String image = imageData?['url'];
        imgs.add(CachedNetworkImage(imageUrl: image));
      });

      setState(() {
        images = imgs;
      });
    });
  }

class _CategoryTab1State extends State<CategoryTab1> {
  List images = [];

  late ScrollController controller;

  final scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  void initState() {
    super.initState();
    // addUrls();
    controller = ScrollController()..addListener(_scrollListener);
    initSliderImages();
    if (this.mounted) {
      context.read<CategoryTab1Bloc>().data.isNotEmpty
          ? print('data already loaded')
          : context.read<CategoryTab1Bloc>().getData(mounted, widget.category);
    }
  }

  @override
  void dispose() {
    controller.removeListener(_scrollListener);
    super.dispose();
  }

  void _scrollListener() {
    print(controller.position.extentAfter);

    if (controller.position.extentAfter < 2) {
      setState(() {
        print('add 2 more');
        print('add 2 more');
        print('add 2 more');
        print('add 2 more');
        // images.addAll(['item1','item2','item3']
            // List.generate(2, (index) => 'Inserted $index'
        // )
 
        // );
      });
    }
  }

  // //
  // void addUrls() {
  //   final List<String> imgs = List.generate(
  //     16,
  //         (_) {
  //       int random = Random().nextInt(16) + 16; // 250-500
  //       return
  //         // initSliderImages();
  //         // 'https://picsum.photos/$random/$random';
  //           'https://firebasestorage.googleapis.com/v0/b/klosterkatz-c914e.appspot.com/o/galerytab1%2F1.png?alt=media&token=5b0e9c74-ec5a-42ca-aa59-309f41938a28';
  //
  //
  //
  //
  //     },
  //   );

  //   setState(() {
  //     images.addAll(imgs);
  //   });
  // }
  //

  // Fetch images from databse for list

  initSliderImages() async {
    final int _limit = 3;

    var result = await FirebaseFirestore.instance.collection('galerytab1');
    result.snapshots().listen((data) {
      List imgs = [];
      data.docChanges.forEach((change) {
        var imageData = change.doc.data();
        String image = imageData?['url'];
        imgs.add(image);
      });

      setState(() {
        images = imgs;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    print('imagesimageimagesimagesimageismageimage');
    print('$images');
    print(images.length);

    return NotificationListener<ScrollNotification>(
      onNotification: (ScrollNotification notification) {


        if (notification.metrics.pixels ==
            notification.metrics.maxScrollExtent) {
          initSliderImages();
          _scrollListener();
          // addUrls();
        }

        return true;
      },
      child:
      ListView.builder(
        controller: controller,
        key: widget.key,
        itemCount: images.length,
        itemExtent: 250,
          itemBuilder: (context, index) {
            return CachedNetworkImage(
              imageUrl: images[index],
              fit: BoxFit.cover,
              key: ValueKey(images[index]),
            );
          }
      ),
    );
  }


}

2

Answers


  1. In listview.Builder add shrinkWrap : primary false if not true

    Login or Signup to reply.
  2. App is crashing due to memory issue. Following code is for proper pagination using firestore. Hope it will help you.

    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:flutter/material.dart';
    import 'package:cached_network_image/cached_network_image.dart';
    
    class CategoryTab1 extends StatefulWidget {
      const CategoryTab1({Key? key}) : super(key: key);
    
      @override
      State<CategoryTab1> createState() => _CategoryTab1State();
    }
    
    class _CategoryTab1State extends State<CategoryTab1> {
      final _controller = ScrollController();
      var _images = <String>[];
    
      /// Flag for first time loading
      var _isLoading = true;
    
      /// Flag for paginated loading
      var _isSubLoading = false;
    
      /// last snapshot reference for pagination
      QueryDocumentSnapshot<Map<String, dynamic>>? _lastSnapshot;
    
      /// length of last images fetched
      var _length = 10;
    
      /// can load more if length is equal or more than 10
      /// if less than 10 it means all images have been fetched
      bool get _canLoadMore => _length >= 10;
    
      @override
      void initState() {
        super.initState();
        _loadData();
        _controller.addListener(_listener);
      }
    
      @override
      void dispose() {
        _controller.removeListener(_listener);
        _controller.dispose();
        super.dispose();
      }
    
      void _listener() {
        if (!_canLoadMore) {
          return;
        }
        if (_isSubLoading || _isLoading) {
          return;
        }
        if (_controller.position.extentAfter <= 0) {
          _loadData();
        }
      }
    
      final _collection = FirebaseFirestore.instance.collection('galerytab1');
    
      void _loadData() async {
        try {
          if (_lastSnapshot != null) {
            _isSubLoading = true;
            setState(() {});
          }
          late QuerySnapshot<Map<String, dynamic>> _result;
    
          /// Fetching images
          if (_lastSnapshot == null) {
            /// First time loading
            _result = await _collection.limit(10).get();
          } else {
            /// Paginated loading
            _result = await _collection
                .startAfterDocument(_lastSnapshot!)
                .limit(10)
                .get();
          }
          final docs = _result.docs;
          _length = docs.length;
          for (final doc in docs) {
            String im = doc.data()['url'] ?? '';
            if (im.isNotEmpty) _images.add(im);
          }
          if (docs.isNotEmpty) _lastSnapshot = docs.last;
        } catch (_) {}
        _isLoading = false;
        _isSubLoading = false;
        setState(() {});
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Column(
            children: [
              Expanded(
                child: ListView.builder(
                  controller: _controller,
                  itemCount: _images.length,
                  addAutomaticKeepAlives: true,
                  itemBuilder: (context, index) {
                    return CachedNetworkImage(
                      imageUrl: _images[index],
                      fit: BoxFit.cover,
                      key: ValueKey(_images[index]),
                    );
                  },
                ),
              ),
              if (_isSubLoading) CircularProgressIndicator(),
            ],
          ),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search