Flutter download audio zip file and play in application - flutter

Hello friend i am new in flutter i need help i have project where almost different zip file hosted on sever every zip file have different audio with categories now i want if user want to download that zip file and extract audio then able to play in application it not visible in phone memory ?here example of code but this is for images and one zip file i take code from this url
https://www.coderzheaven.com/2019/06/07/download-zip-extract-it-and-show-the-images-file-in-list-in-ui/
here my code
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:archive/archive.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
class DownloadAssetsDemo extends StatefulWidget {
DownloadAssetsDemo() : super();
final String title = "Download & Extract ZIP Demo";
#override
DownloadAssetsDemoState createState() => DownloadAssetsDemoState();
}
class DownloadAssetsDemoState extends State<DownloadAssetsDemo> {
//
bool _downloading;
String _dir;
List<String> _images, _tempImages;
String _zipPath = 'https://coderzheaven.com/youtube_flutter/images.zip';
String _localZipFileName = 'images.zip';
#override
void initState() {
super.initState();
_images = List();
_tempImages = List();
_downloading = false;
_initDir();
}
_initDir() async {
if (null == _dir) {
_dir = (await getApplicationDocumentsDirectory()).path;
}
}
Future<File> _downloadFile(String url, String fileName) async {
var req = await http.Client().get(Uri.parse(url));
var file = File('$_dir/$fileName');
return file.writeAsBytes(req.bodyBytes);
}
Future<void> _downloadZip() async {
setState(() {
_downloading = true;
});
_images.clear();
_tempImages.clear();
var zippedFile = await _downloadFile(_zipPath, _localZipFileName);
await unarchiveAndSave(zippedFile);
setState(() {
_images.addAll(_tempImages);
_downloading = false;
});
}
unarchiveAndSave(var zippedFile) async {
var bytes = zippedFile.readAsBytesSync();
var archive = ZipDecoder().decodeBytes(bytes);
for (var file in archive) {
var fileName = '$_dir/${file.name}';
if (file.isFile) {
var outFile = File(fileName);
//print('File:: ' + outFile.path);
_tempImages.add(outFile.path);
outFile = await outFile.create(recursive: true);
await outFile.writeAsBytes(file.content);
}
}
}
buildList() {
return Expanded(
child: ListView.builder(
itemCount: _images.length,
itemBuilder: (BuildContext context, int index) {
return Image.file(
File(_images[index]),
fit: BoxFit.fitWidth,
);
},
),
);
}
progress() {
return Container(
width: 25,
height: 25,
padding: EdgeInsets.fromLTRB(0.0, 20.0, 10.0, 20.0),
child: CircularProgressIndicator(
strokeWidth: 3.0,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: <Widget>[
_downloading ? progress() : Container(),
IconButton(
icon: Icon(Icons.file_download),
onPressed: () {
_downloadZip();
},
),
],
),
body: Container(
child: Column(
children: <Widget>[
buildList(),
],
),
),
);
}
}

_initDir() async {
if (null == _dir) {
_dir = (await getApplicationDocumentsDirectory()).path;
print("current dir--$_dir")
}
}
use like this

Related

Flutter: Catch data over Websocket, save it inside a Json and display it in a Chart

I hope somebody can help me out on a problem that i have.
I try to explain the problem the best i can.
The idea is the following for a Desktop App
First i tried to fetch and save data locally in a Json file that i get over WebSocket. What is working.
Second i tried to display the data of the local Json file inside a Chart. What is also working.
After i tried to combine the two above scenarios i one app and here i get the following error.
Exception has occurred.
FileSystemException (FileSystemException: read failed, path = 'C:\Users\7ke19\Documents/Measure/measure.json' (OS Error: The process cannot access the file because another process has locked a portion of the file.
, errno = 33))
In my app i am using the following packages.
Getx for the state manegment. https://pub.dev/packages/get
Localstorage for the Json storage. https://pub.dev/packages/localstorage
Syncfusion_flutter_charts for the Chart. https://pub.dev/packages/syncfusion_flutter_charts
Path_provider to get access to file and folders. https://pub.dev/packages/path_provider
I think i get the above error because at some moment inside my code the app is trying to read a write to the file at the same time.
Follows the code that i have.
The code is divided in three separated files.
Main Function:
import 'package:flutter/material.dart';
import 'package:flutter_application_2/controller/diagram_controller.dart';
import 'package:flutter_application_2/home_screen.dart';
import 'package:get/get.dart';
void main() async {
Get.put(DiagramController());
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const GetMaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
);
}
}
HomeScreen:
import 'package:flutter_application_2/controller/diagram_controller.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: GetBuilder<DiagramController>(
init: DiagramController(),
initState: (_) {},
builder: (gtxs1) {
return FutureBuilder(
future: gtxs1.getJsonData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
//********Showing if Websocket is Connected or Disconnected*******
child: gtxs1.connectedS1Status
? const Text(
"WEBSOCKET: CONNECTED",
style: TextStyle(
fontSize: 18,
color: Colors.green,
),
)
: const Text(
"WEBSOCKET: DISCONNECTED",
style: TextStyle(
fontSize: 18,
color: Colors.red,
),
),
),
//**********************Showing Range Diagram **********************
Column(
children: [
const Text(
'Range Diagram:',
),
const SizedBox(
height: 5,
),
SizedBox(
width: 800,
height: 280,
child: SfCartesianChart(
title: ChartTitle(
borderWidth: 2,
alignment: ChartAlignment.near,
),
series: gtxs1.getSeriesRange(),
legend: Legend(isVisible: true),
),
),
],
),
const SizedBox(
height: 20,
),
//**********************Showing Force Diagram **********************
Column(
children: [
const Text(
'Force Diagram:',
),
const SizedBox(
height: 5,
),
SizedBox(
width: 800,
height: 280,
child: SfCartesianChart(
title: ChartTitle(
borderWidth: 2,
alignment: ChartAlignment.near,
),
series: gtxs1.getSeriesForce(),
legend: Legend(isVisible: true),
),
),
],
),
],
);
} else {
return const CircularProgressIndicator();
}
},
);
},
),
);
}
}
Controller:
// ignore_for_file: avoid_print
import 'package:get/get.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'package:path_provider/path_provider.dart';
import 'package:web_socket_channel/io.dart';
import 'package:localstorage/localstorage.dart';
final MeasureList list = MeasureList(); //List for LocalStorage
bool initialized = false; //for LocalStorage
int istcyclesJson = 0; //variable for istcycles
List<dynamic> istrangesensorJson = [0]; //variable for istrangesensor
List<dynamic> istforcesensorJson = [0]; //variable for istforcesensor
//***********************************************************************************************
//-----class MeasureItem for LocalStorage--------------------------------------------------------
//***********************************************************************************************
class MeasureItem {
int titleCountJson;
List<dynamic> titleRangeJson;
List<dynamic> titleForceJson;
MeasureItem({
required this.titleCountJson,
required this.titleRangeJson,
required this.titleForceJson,
});
toJSONEncodable() {
Map<String, dynamic> m = {};
m['count_array'] = titleCountJson;
m['range_array'] = titleRangeJson;
m['force_array'] = titleForceJson;
return m;
}
}
//***********************************************************************************************
//-----class MeasureList for LocalStorage--------------------------------------------------------
//***********************************************************************************************
class MeasureList {
List<MeasureItem> items = [];
toJSONEncodable() {
return items.map((item) {
return item.toJSONEncodable();
}).toList();
}
}
class DiagramController extends GetxController {
static DiagramController get to => Get.find();
List<List<ChartDataRange>> dataListRange = [];
List<List<ChartDataForce>> dataListForce = [];
LocalStorage storage = LocalStorage('/Measure/measure.json');
final MeasureList list = MeasureList();
late IOWebSocketChannel channel;
late bool connectedS1Status;
Directory? rootPath;
//**********************************************************************
#override
void onInit() {
connectedS1Status = false;
createFileFolder();
Future.delayed(
Duration.zero,
() async {
channelconnect();
},
);
Future.delayed(
const Duration(milliseconds: 1000),
() async {
loadStringRange();
loadStringForce();
},
);
super.onInit();
}
//***********************************************************************************************
//-----Channelconnect----------------------------------------------------------------------------
//***********************************************************************************************
channelconnect() {
try {
channel = IOWebSocketChannel.connect("ws://192.168.1.100:80");
channel.stream.listen(
(message) {
print(message);
Map<String, dynamic> jsondat = json.decode(message);
String data = json.encode(jsondat);
if (data.contains("cycle")) {
connectedS1Status = true;
update();
}
if (data.contains("count_array")) {
istcyclesJson = jsondat['count_array'];
istrangesensorJson = jsondat['range_array'];
istforcesensorJson = jsondat['force_array'];
_save();
//update();
}
},
onDone: () {
print("Web socket is closed");
connectedS1Status = false;
},
onError: (error) {
print(error.toString());
},
);
} catch (_) {
print("error on connecting to websocket.");
}
//update();
}
//***********************************************************************************************
//-----Functions to create and generate Json List using LocalStorage-----------------------------
//***********************************************************************************************
//...................................................
void _save() {
_addItem(istcyclesJson, istrangesensorJson, istforcesensorJson);
print("SAVE");
// update();
}
//...................................................
_addItem(int titlecount, List<dynamic> titlerange, List<dynamic> titleforce) {
final item = MeasureItem(
titleCountJson: titlecount,
titleRangeJson: titlerange,
titleForceJson: titleforce);
list.items.add(item);
_saveToStorage();
//update();
}
//...................................................
_saveToStorage() {
storage.setItem('measure', list.toJSONEncodable());
//update();
}
//***********************************************************************************************
//-----Functions to create Folder and File if not exist and write to the file some zero values
//-----not to get error when display the chart and the file is empty
//***********************************************************************************************
Future<File> createFileFolder() async {
rootPath = await getApplicationDocumentsDirectory();
Directory sampleFolder = Directory('${rootPath!.path}/Measure');
if (!sampleFolder.existsSync()) {
sampleFolder.createSync();
}
File sampleFile =
await File('${sampleFolder.path}/measure.json').create(recursive: true);
if (!sampleFile.existsSync()) {
sampleFolder.createSync();
}
final file = sampleFile;
return file.writeAsString(
'{"measure": [{"count": 0,"range_array": [0,0,0],"force_array": [0,0,0]}]}');
}
//**********************************************************************
Future<String> getJsonData() async {
rootPath = await getApplicationDocumentsDirectory();
Directory sampleFolder = Directory('${rootPath!.path}/Measure');
await File('${sampleFolder.path}/measure.json').create(recursive: true);
return await File('${sampleFolder.path}/measure.json').readAsString();
}
//**********************************************************************
Future loadStringRange() async {
final String jsonString = await getJsonData();
final dynamic jsonResponse = json.decode(jsonString);
List<dynamic> values = jsonResponse['measure'].last['range_array'];
List<ChartDataRange> chartDataR = [];
for (var j = 0; j < values.length; j++) {
chartDataR.add(ChartDataRange(j, values[j]));
}
dataListRange.add(chartDataR);
update();
}
//**********************************************************************
Future loadStringForce() async {
final String jsonString = await getJsonData();
final dynamic jsonResponse = json.decode(jsonString);
List<dynamic> values = jsonResponse['measure'].last['force_array'];
List<ChartDataForce> chartDataF = [];
for (var j = 0; j < values.length; j++) {
chartDataF.add(ChartDataForce(j, values[j]));
}
dataListForce.add(chartDataF);
update();
}
//**********************************************************************
List<ChartSeries<ChartDataRange, num>> getSeriesRange() {
List<ChartSeries<ChartDataRange, num>> seriesListRange = [];
for (var index = 0; index < dataListRange.length; index++) {
seriesListRange.add(
SplineSeries<ChartDataRange, num>(
dataSource: dataListRange[index],
xValueMapper: (ChartDataRange data, _) => data.x,
yValueMapper: (ChartDataRange data, _) => data.y,
),
);
}
return seriesListRange;
}
//**********************************************************************
List<ChartSeries<ChartDataForce, num>> getSeriesForce() {
List<ChartSeries<ChartDataForce, num>> seriesListForce = [];
for (var index = 0; index < dataListForce.length; index++) {
seriesListForce.add(
SplineSeries<ChartDataForce, num>(
dataSource: dataListForce[index],
xValueMapper: (ChartDataForce data, _) => data.x,
yValueMapper: (ChartDataForce data, _) => data.y,
),
);
}
return seriesListForce;
}
}
//**********************************************************************
class ChartDataRange {
final num x;
final num y;
ChartDataRange(this.x, this.y);
}
//**********************************************************************
class ChartDataForce {
final num x;
final num y;
ChartDataForce(this.x, this.y);
}

Linear Progress indicator could not manage its state while downloading files

I am new to Flutter and am currently working on a Flutter app that downloads files from given links. The issue is that when only one link app is working fine but when more than one link arrive file does not download. I receive the link data in json file then I parsed the json and used these links inside the listview.builder. I tried very much but could not find the solution. Here is the code for the screen. Main issue is that I think state is not managed well.
dsharing.json file contain name and links of files
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import '../services/services.dart';
class ReceiveScreen extends StatefulWidget {
const ReceiveScreen({Key? key, }) : super(key: key);
#override
State<ReceiveScreen> createState() => _ReceiveScreenState();
}
class _ReceiveScreenState extends State<ReceiveScreen> {
Map<int, double> progress = {};
int received = 0;
int total = 0;
var _url = "http://192.168.1.100:50500";
List<Receiver> receivers = [];
#override
initState()
{
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Receive Files"),
) ,
body: Column(
children: [
ElevatedButton(
onPressed: ()async
{
await getUrls();
},
child: const Text("Get Response")
),
Text(rsponse),
FutureBuilder(
future: getUrls(),
builder: (context, AsyncSnapshot<Files> snapshot)
{
if(!snapshot.hasData)
{
return const Center(child: CircularProgressIndicator());
}
Files files = snapshot.data!;
return ListView.builder(
itemCount: files.names!.length,
shrinkWrap: true,
itemBuilder: (context, index)
{
return Column(
children: [
ElevatedButton(
onPressed: () async
{
final path = "/storage/emulated/0/Download/${files.names![index]}";
await Dio().download(
files.urls![index],
path,
onReceiveProgress: (received, total)
{
progress[index] = received/total;
}
);
},
child: Text("${files.names![index] } Download")
),
LinearProgressIndicator(
value: progress[index],
minHeight: 20,
)
],
);
}
);
}
)
],
)
);
}
String rsponse = "";
fetchDataApi() async
{
var response = await get(Uri.parse("$_url/dsharing.json"));
if(response.statusCode == 200)
{
return jsonDecode(response.body);
}
}
Future<Files> getUrls() async
{
var data = await fetchDataApi();
return Files.fromJson(data, _url);
}
}
class Files
{
final List? names;
final List? urls;
Files({ this.names, this.urls});
factory Files.fromJson(Map map, String url)
{
var fileNames = [];
String name = map['name'];
if(name.contains(":"))
{
int index = name.indexOf(":") + 1;
name = name.substring(index + 1, name.length);
var x = name.replaceAll(" ", '^*&');
fileNames = x.split("^*&").toList();
}
else
{
fileNames.add(name);
}
var x = map['data'].toString().split("|dsharing|").toList();
var fileUrls = x.map((i) => url + "?/q="+ i).toList();
return Files(
names: fileNames,
urls: fileUrls
);
}
}

Error opening PDF file after downloading from server Flutter

Hello I have a screen in the app that downloads a PDF file and displays the download progress in percent. After downloading, the file is opened using the package of pdf_render: ^ 1.0.10. Sometimes it opens and displays the PDF file and sometimes it does not open the file and I have a blank screen. I have no fault in the console and I do not know what the fault is. Thank you
Flutter App :
class Web_view_vehicle extends StatefulWidget {
var choice ;
var name_vehicle;
Web_view_vehicle({ required this.choice , this.name_vehicle}) : super();
#override
_Web_view_vehicleState createState() => _Web_view_vehicleState();
}
class _Web_view_vehicleState extends State<Web_view_vehicle> {
bool downloading = false;
String progressString = "";
String path = '';
late List data ;
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/teste.pdf');
}
Future<File> writeCounter(Uint8List stream) async {
final file = await _localFile;
// Write the file
return file.writeAsBytes(stream);
}
Future<Uint8List> fetchPost() async {
Dio dio = Dio();
var response = await dio.get(widget.choice,
onReceiveProgress: (rec, total) {
print("Rec: $rec , Total: $total");
if(!mounted)return;
setState(() {
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
});
},options: Options(responseType: ResponseType.bytes));
final responseJson = response.data;
if (!mounted) {
}
setState(() {
downloading = false;
progressString = "Completed";
});
print("Download completed");
return responseJson;
}
loadPdf() async {
writeCounter((await fetchPost()));
path = (await _localFile).path;
if (!mounted) return;
setState(() {});
}
#override
void initState() {
super.initState();
loadPdf();
}
#override
Widget build(BuildContext context) {
Color? bgColor = Colors.grey[300];
return Scaffold(
backgroundColor: bgColor,
appBar: AppBar(
leading: Padding(
padding: const EdgeInsets.fromLTRB(5.0 , 0.0 , 0.0 , 0.0),
child: new IconButton(
icon: new Icon(Icons.arrow_back),
onPressed: (){Navigator.pop(context,true);}
),
),
title: Text('מדריך לרכב ${widget.name_vehicle}',textAlign: TextAlign.center,textDirection: TextDirection.rtl,),
backgroundColor: Colors.red[400],
centerTitle: true,
actions: <Widget>[
],
),
body:
(path.length > 5)?
PdfViewer.openFile(path,
):
Center(child: Column(crossAxisAlignment: CrossAxisAlignment.center,mainAxisAlignment: MainAxisAlignment.center,mainAxisSize: MainAxisSize.max,
children: [
CircularProgressIndicator(),
Text('טוען מדריך ${progressString}',textDirection: TextDirection.rtl,textAlign: TextAlign.center,)
],
))
);
}
}

Download ZIP, Extract it and Show the images file but not load from Document Directory?

Hello friend I am creating project when user install my app first they download zip file from internet and extract all file inside it then show in my app but problem is that when user download and extracted file the image inside zip shown in app when I close app and reopen it again image not load from Document directory everytime they need click on download button then show the image in the app any one tell me what's issue here is code?
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:archive/archive.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
class DownloadAssetsDemo extends StatefulWidget {
DownloadAssetsDemo() : super();
final String title = "Download & Extract ZIP Demo";
#override
DownloadAssetsDemoState createState() => DownloadAssetsDemoState();
}
class DownloadAssetsDemoState extends State<DownloadAssetsDemo> {
//
bool _downloading;
String _dir;
List<String> _images, _tempImages;
String _zipPath = 'https://coderzheaven.com/youtube_flutter/images.zip';
String _localZipFileName = 'images.zip';
#override
void initState() {
super.initState();
_images = List();
_tempImages = List();
_downloading = false;
_initDir();
}
_initDir() async {
if (null == _dir) {
_dir = (await getApplicationDocumentsDirectory()).path;
}
}
Future<File> _downloadFile(String url, String fileName) async {
var req = await http.Client().get(Uri.parse(url));
var file = File('$_dir/$fileName');
return file.writeAsBytes(req.bodyBytes);
}
Future<void> _downloadZip() async {
setState(() {
_downloading = true;
});
_images.clear();
_tempImages.clear();
var zippedFile = await _downloadFile(_zipPath, _localZipFileName);
await unarchiveAndSave(zippedFile);
setState(() {
_images.addAll(_tempImages);
_downloading = false;
});
}
unarchiveAndSave(var zippedFile) async {
var bytes = zippedFile.readAsBytesSync();
var archive = ZipDecoder().decodeBytes(bytes);
for (var file in archive) {
var fileName = '$_dir/${file.name}';
if (file.isFile) {
var outFile = File(fileName);
//print('File:: ' + outFile.path);
_tempImages.add(outFile.path);
outFile = await outFile.create(recursive: true);
await outFile.writeAsBytes(file.content);
}
}
}
buildList() {
return Expanded(
child: ListView.builder(
itemCount: _images.length,
itemBuilder: (BuildContext context, int index) {
return Image.file(
File(_images[index]),
fit: BoxFit.fitWidth,
);
},
),
);
}
progress() {
return Container(
width: 25,
height: 25,
padding: EdgeInsets.fromLTRB(0.0, 20.0, 10.0, 20.0),
child: CircularProgressIndicator(
strokeWidth: 3.0,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: <Widget>[
_downloading ? progress() : Container(),
IconButton(
icon: Icon(Icons.file_download),
onPressed: () {
_downloadZip();
},
),
],
),
body: Container(
child: Column(
children: <Widget>[
buildList(),
],
),
),
);
}
}
You can copy paste run full code below
You can save and restore List<String> with package SharedPreferences
code snippet
getHistoryImageList() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_images = prefs.getStringList("images");
});
}
...
Future<void> _downloadZip() async {
...
await unarchiveAndSave(zippedFile);
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setStringList("images", _tempImages);
setState(() {
_images = List<String>.from(_tempImages);
_downloading = false;
});
}
working demo
full code
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:archive/archive.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
class DownloadAssetsDemo extends StatefulWidget {
DownloadAssetsDemo() : super();
final String title = "Download & Extract ZIP Demo";
#override
DownloadAssetsDemoState createState() => DownloadAssetsDemoState();
}
class DownloadAssetsDemoState extends State<DownloadAssetsDemo> {
//
bool _downloading;
String _dir;
List<String> _images, _tempImages;
String _zipPath = 'https://coderzheaven.com/youtube_flutter/images.zip';
String _localZipFileName = 'images.zip';
getHistoryImageList() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_images = prefs.getStringList("images");
});
}
#override
void initState() {
super.initState();
_images = [];
getHistoryImageList();
_tempImages = List();
_downloading = false;
_initDir();
}
_initDir() async {
if (null == _dir) {
_dir = (await getApplicationDocumentsDirectory()).path;
print("init $_dir");
}
}
Future<File> _downloadFile(String url, String fileName) async {
var req = await http.Client().get(Uri.parse(url));
var file = File('$_dir/$fileName');
print("file.path ${file.path}");
return file.writeAsBytes(req.bodyBytes);
}
Future<void> _downloadZip() async {
setState(() {
_downloading = true;
});
_images?.clear();
_tempImages?.clear();
var zippedFile = await _downloadFile(_zipPath, _localZipFileName);
await unarchiveAndSave(zippedFile);
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setStringList("images", _tempImages);
setState(() {
_images = List<String>.from(_tempImages);
_downloading = false;
});
}
unarchiveAndSave(var zippedFile) async {
var bytes = zippedFile.readAsBytesSync();
var archive = ZipDecoder().decodeBytes(bytes);
for (var file in archive) {
var fileName = '$_dir/${file.name}';
print("fileName ${fileName}");
if (file.isFile && !fileName.contains("__MACOSX")) {
var outFile = File(fileName);
//print('File:: ' + outFile.path);
_tempImages.add(outFile.path);
outFile = await outFile.create(recursive: true);
await outFile.writeAsBytes(file.content);
}
}
}
buildList() {
return _images == null
? Container()
: Expanded(
child: ListView.builder(
itemCount: _images.length,
itemBuilder: (BuildContext context, int index) {
return Image.file(
File(_images[index]),
fit: BoxFit.fitWidth,
);
},
),
);
}
progress() {
return Container(
width: 25,
height: 25,
padding: EdgeInsets.fromLTRB(0.0, 20.0, 10.0, 20.0),
child: CircularProgressIndicator(
strokeWidth: 3.0,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: <Widget>[
_downloading ? progress() : Container(),
IconButton(
icon: Icon(Icons.file_download),
onPressed: () {
_downloadZip();
},
),
],
),
body: Container(
child: Column(
children: <Widget>[
buildList(),
],
),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: DownloadAssetsDemo(),
);
}
}

How to get path of an Asset object in Flutter?

I am using multi-image picker in flutter and i have to load these images in a file to display them in a Photo View..
I am certain that my method to convert the assets to files is not appropriate.
I am not able to achieve this as i am always getting file not found exception .
This is my code:
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:photo_view/photo_view.dart';
import 'package:flutter_absolute_path/flutter_absolute_path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
void main() => runApp(AddPost());
class AddPost extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<AddPost> {
List<Asset> images = List<Asset>();
//File images;
List<File>files=List<File>();
String _error = 'No Error Dectected';
var width;
var height;
#override
void initState() {
super.initState();
}
void getFileList() async {
for (int i = 0; i < images.length; i++) {
String filename=images[i].name;
String dir = (await getApplicationDocumentsDirectory()).path;
String path='$dir/$filename';
var path2 = await FlutterAbsolutePath.getAbsolutePath(path);
//var path = await images[i].filePath; ( the file path thing is not found)
print(path2);
var file = await getImageFileFromAsset(path2);
print(file);
files.add(file);
}
}
Future<File> getImageFileFromAsset(String path) async {
final file = File(path);
return file;
}
Widget buildGridView() {
return new Swiper(
loop: false,
itemCount: files==null?0:files.length,
pagination: new SwiperPagination(
// margin: new EdgeInsets.all(5.0),
builder: new DotSwiperPaginationBuilder(
color: Colors.purple, activeColor: Colors.green)),
itemBuilder: (BuildContext context, int index) {
return Container(
child: PhotoView(
gaplessPlayback: false,
backgroundDecoration: BoxDecoration(color: Colors.transparent),
minScale: PhotoViewComputedScale.contained ,
maxScale: PhotoViewComputedScale.covered ,
imageProvider: ,
));
}
);
}
Future<void> loadAssets() async {
List <Asset>resultList ;
try {
resultList = await MultiImagePicker.pickImages(
maxImages: 6,
enableCamera: true,
selectedAssets: images,
cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
materialOptions: MaterialOptions(
actionBarColor: "#abcdef",
actionBarTitle: "Example App",
allViewTitle: "All Photos",
useDetailsView: false,
selectCircleStrokeColor: "#000000",
));
} on Exception catch (e) {
error = e.toString();
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
images = resultList;
_error = error;
getFileList();
});
}
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: const Text('Plugin example app'),
),
body: Column(
children: <Widget>[
Center(child: Text('Error: $_error')),
RaisedButton(
child: Text("Pick images"),
onPressed: loadAssets,
),
Expanded(
child: buildGridView(),
),
],
),
),
);
}
}
These are the errors im getting:
java.io.FileNotFoundException: No content provider: /data/user/0/xperience.flutter_app/app_flutter/Camera
in addition to:
Unhandled Exception: MissingPluginException(No implementation found for method getAbsolutePath on channel flutter_absolute_path)
Any help is appreciated.
I resolved my issue by putting images[i].identifier
void getFileList() async {
files.clear();
for (int i = 0; i < images.length; i++) {
var path2 = await FlutterAbsolutePath.getAbsolutePath(images[i].identifier);
//var path = await images[i].filePath;
print(path2);
var file = await getImageFileFromAsset(path2);
print(file);
files.add(file);
}
}