1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] Image Cache in Flutter

Discussão em 'Mobile' iniciado por Stack, Outubro 16, 2024 às 18:53.

  1. Stack

    Stack Membro Participativo

    I'm new to Flutter and currently stuck on an image loading problem. In my application I'm querying feed posts from a firebase dataserver, which contain a URL to an image. When scrolling down new posts are getting loaded and currently the old ones seem to be getting destroyed and need to get downloaded again when scrolling up. Is there a quick solution to cache the images to reduce bandwith traffic?

    Thanks in advance!

    This is my code:

    class Feed extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
    return Scaffold(
    body: StreamBuilder<List<Post>>(
    stream: FeedService().getPosts(), application layer
    builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
    return Center(child: CircularProgressIndicator());
    }
    if (snapshot.hasError) {
    return Center(child: Text('Error: ${snapshot.error}'));
    }
    if (!snapshot.hasData || snapshot.data!.isEmpty) {
    return Center(child: Text('No posts available'));
    }

    final posts = snapshot.data!;

    return ListView.builder(
    itemCount: posts.length,
    itemBuilder: (context, index) {
    return PostItem(post: posts[index]);
    },
    );
    },
    ),
    floatingActionButton: FloatingActionButton(
    onPressed: () {
    Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => CreatePostScreen()),
    );
    },
    child: Icon(Icons.add),
    heroTag: 'createPostButton'
    ),
    );
    }
    }

    class PostItem extends StatefulWidget {
    final Post post;

    PostItem({required this.post});

    @override
    State<PostItem> createState() => _PostItemState();
    }

    class _PostItemState extends State<PostItem> {
    bool _isBookmarked = false;
    bool _isLiked = false;

    @override
    Widget build(BuildContext context) {
    return Card(
    margin: const EdgeInsets.all(10),
    child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [

    ListTile(
    leading: CircleAvatar(
    backgroundImage: NetworkImage(widget.post.userProfileImageUrl),
    ),
    title: Text(widget.post.username),
    subtitle: Text(widget.post.timestamp.toDate().toString()),
    trailing: Icon(Icons.more_vert),
    ),

    CachedNetworkImage(
    imageUrl: widget.post.imageUrl,
    fit: BoxFit.cover,
    width: double.infinity,
    cacheManager: CacheManager(
    Config(
    'customCacheKey',
    stalePeriod: Duration(days: 7),
    maxNrOfCacheObjects: 100,
    ),
    ),
    placeholder: (context, url) => Center(child: CircularProgressIndicator()),
    errorWidget: (context, url, error) => Icon(Icons.error),
    ),

    // Like and comment section
    Padding(
    padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10),
    child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    children: [
    Row(
    children: [
    IconButton(
    onPressed: () {
    setState(() {
    _isLiked = !_isLiked;
    });
    },
    icon: Icon(_isLiked ? Icons.thumb_up : Icons.thumb_up_outlined),
    ),
    const SizedBox(width: 10),
    IconButton(
    onPressed: () {},
    icon: const Icon(Icons.comment_outlined),
    ),
    ],
    ),
    IconButton(
    onPressed: () {
    setState(() {
    _isBookmarked = !_isBookmarked;
    });
    },
    icon: Icon(_isBookmarked ? Icons.bookmark : Icons.bookmark_outline),
    )
    ],
    ),
    ),

    // Post caption or text (if needed)
    Padding(
    padding: const EdgeInsets.symmetric(horizontal: 16.0),
    child: Text(
    widget.post.description,
    style: TextStyle(fontSize: 16),
    ),
    ),
    const SizedBox(height: 10),
    ],
    ),
    );
    }
    }

    Continue reading...

Compartilhe esta Página