본문 바로가기
Flutter

[Flutter] convert network image to file ; 네트워크 이미지를 File로 변환하기

by hymndaniel 2022. 5. 11.

Motivation

네트워크(서버에서 url로 받은)이미지를 파일로 변경해서 사용하고 싶을때

아래 메서드로 변경 가능

 

import 'dart:io';   
import 'package:dio/dio.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';


Future<File> getImage({required String url}) async {
  /// Get Image from server
  final Response res = await Dio().get<List<int>>(
    url,
    options: Options(
        responseType: ResponseType.bytes,
      ),
    );

    /// Get App local storage
    final Directory appDir = await getApplicationDocumentsDirectory();

    /// Generate Image Name
    final String imageName = url.split('/').last;

    /// Create Empty File in app dir & fill with new image
    final File file = File(join(appDir.path, imageName));

    file.writeAsBytesSync(res.data as List<int>);

    return file;
}
 

 

 

Reference

https://stackoverflow.com/questions/63353484/flutter-network-image-to-file

 

Flutter - Network Image to File

I have an Image URL like "https://example.com/xyz.jpg". Now I want to put the image in a File type variable; Something along these lines: File f = File("https://example.com/xyz.jpg&q...

stackoverflow.com

 

 
728x90