In many cases, we may have to display images in our Flutter app that are protected by web middleware and require a token to access them. In this tutorial, we’ll see how to accomplish this using the Image.network
widget along with an authentication mechanism to pass the token to the server.
Prerequisites
Before we get started, make sure you have the following:
- Flutter installed on your system.
- An image URL that is protected by web middleware and requires a token to access it.
- A valid authentication token for the image URL.
The Code
Here is an example code snippet that demonstrates how to display protected images with tokens in Flutter:
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; class ImageWithToken extends StatefulWidget { final String imageUrl; final String token; const ImageWithToken({Key? key, required this.imageUrl, required this.token}) : super(key: key); @override _ImageWithTokenState createState() => _ImageWithTokenState(); } class _ImageWithTokenState extends State<ImageWithToken> { late http.Response _response; late String _imageBase64; @override void initState() { super.initState(); _fetchImage(); } Future<void> _fetchImage() async { _response = await http.get( Uri.parse(widget.imageUrl), headers: {HttpHeaders.authorizationHeader: 'Bearer ${widget.token}'}, ); setState(() { _imageBase64 = base64Encode(_response.bodyBytes); }); } @override Widget build(BuildContext context) { return _imageBase64.isNotEmpty ? Image.memory( base64Decode(_imageBase64), ) : const CircularProgressIndicator(); } }