skip to Main Content

I have a binary file I need to read its contents using retrofit for my flutter application.

I want to know if this could be possible or not.
if yes, any links, please?

Otherwise, I need some recommendations.

Thanks in advance for your help

2

Answers


  1. First of all, you have to specify your retrofit client and specify your API inside and specify ReturnType.bytes by DioResponseType annotation

    I’ll make a simple example for downloading the image from the https://www.phoca.cz web site and in the same way you can download any type of files

    part 'rest_client.g.dart';
    
    @RestApi(baseUrl: "https://www.phoca.cz/")
    abstract class RestClient {
      factory RestClient(Dio dio, {String baseUrl}) = _RestClient;
    
      @GET("images/phocadownloadsite/phocadownload-category-view-bootstrap-mobile-mobile-view.png")
      @DioResponseType(ResponseType.bytes)
      Future<HttpResponse<List<int>>> downloadFile();
    }
    

    Generate a code by

    flutter pub run build_runner run
    

    Initialise a client

    final dio = Dio(); 
    final client = RestClient(dio);
    final response = await client.downloadFile();
    

    And you can obtain the image through Image.memory

    Future<void> main() async {
      final dio = Dio();
      final client = RestClient(dio);
      final response = await client.downloadFile();
      WidgetsFlutterBinding.ensureInitialized();
    
      runApp(MaterialApp(
        home: Scaffold(
          body: Center(
            child: Image.memory(response.response.data),
          ),
        ),
      ));
    }
    

    enter image description here

    Login or Signup to reply.
  2. The answer given by powerman23rus works perfectly with retrofit, but if you are looking for a package that requires less code, u can try the http package (https://pub.dev/packages/http) which doesn’t require tags or generated files. You can receive an image like this:

    import 'package:http/http.dart' as http;
    
    late http.Response response;
      response = await http
          .get(
        Uri.parse("https://www.example.com/Cards/GetRandom.png"),
        headers: {"Authorization":"Bearer "+token}
      )
          .timeout(const Duration(seconds: 7));
    Uint8List image = response.bodyBytes;
    

    Once obtained, you can use this widget to render the image:

    Image.memory(image)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search