Categories
Mobile App Development

How to Display Protected Images with Tokens in Flutter

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();
  }
}

In this example, we define a new ImageWithToken widget that takes two required parameters: imageUrl, which is the URL of the protected image, and token, which is the authentication token required to access the image.

In the _fetchImage method, we use the http package to make a GET request to the image URL, passing in the authentication token in the request headers. Once we have the response, we convert the image data to base64 encoding and store it in the _imageBase64 variable.

Finally, in the build method, we display a CircularProgressIndicator while the image data is being fetched, and once the _imageBase64 variable is not empty, we display the image using the Image.memory widget, decoding the base64-encoded image data.

Conclusion

In this tutorial, we learned how to display protected images with tokens in Flutter using the Image.network widget and an authentication mechanism to pass the token to the server. By using this approach, we can display images that are protected by web middleware and require a token to access them.

Leave a Reply

Your email address will not be published. Required fields are marked *