How do i access this variable in flutter? - flutter

I am using a barcode package in flutter and it has a variable in it's class it is showing nothing when used.
this is the code of the model:
class ScanResult {
ScanResult({
this.type = ResultType.Barcode,
this.rawContent = '',
this.format = BarcodeFormat.unknown,
this.formatNote = '',
});
final ResultType type;
final String rawContent;
final BarcodeFormat format;
final String formatNote;
}
And this is the code of the screen:
class _MyAppState extends State<MyApp> {
int total = 22;
// todo scanner
ScanResult scanResult = ScanResult();
var _aspectTolerance = 0.00;
var _numberOfCameras = 0;
var _selectedCamera = -1;
var _useAutoFocus = true;
var _autoEnableFlash = false;
static final _possibleFormats = BarcodeFormat.values.toList()
..removeWhere((e) => e == BarcodeFormat.unknown);
List<BarcodeFormat> selectedFormats = [..._possibleFormats];
Future<void> _scan() async {
try {
final result = await BarcodeScanner.scan(
options: ScanOptions(
restrictFormat: selectedFormats,
useCamera: _selectedCamera,
autoEnableFlash: _autoEnableFlash,
android: AndroidOptions(
aspectTolerance: _aspectTolerance,
useAutoFocus: _useAutoFocus,
),
),
);
setState(() { scanResult = result;});
} on PlatformException catch (e) {
setState(() {
scanResult = ScanResult(
type: ResultType.Error,
format: BarcodeFormat.unknown,
rawContent: e.code == BarcodeScanner.cameraAccessDenied
? 'The user did not grant the camera permission!'
: 'Unknown error: $e',
);
});
}
}
Widget build(BuildContext context) {
final scanResult = this.scanResult;
return MaterialApp(
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: const Text('Material App Bar'),
),
body: Center(
child: Container(
child: Column(
children: [
TextButton(
onPressed: () async {
await _scan();
setState(() {
if (total.toString() == scanResult.rawContent) {
print("success");
print(scanResult.rawContent);
} else {
print("shitt");
print(total.toString());
print(scanResult.rawContent);
}
});
},
child: Text("scan")),
Text(scanResult.rawContent),
],
),
),
),
),
);
}
}
the if statement is not working, and print(scanResult.rawContent) not working, please help I don't know how to access that variables. I am new to flutter.

Related

How to write data to the firebase realtime database inside a widget loop?

Hi everyone,
I'm new to flutter and I am stuck in this code. I want to multipy a row widget based on the user input and I've tested that using 'for' loop. But I don't know how to read, write and update data in seperate rows inside the widget loop. Here is my code (home.dart)
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:hexos_automation/constants/routes.dart';
import 'package:hexos_automation/enums/menu_action.dart';
import 'package:hexos_automation/services/auth/auth_service.dart';
import 'package:hexos_automation/utilities/show_error_dialog.dart';
class HomeView extends StatefulWidget {
const HomeView({Key? key}) : super(key: key);
#override
State<HomeView> createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
String email = 'Loading...';
String mID = 'Loading...';
String switchState = 'OFF';
String listSwitchState = 'OFF';
late int i;
#override
void initState() {
super.initState();
readUserData();
readListSwitchStatus();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home'),
actions: [
PopupMenuButton<MenuAction>(
onSelected: (value) async {
switch (value) {
case MenuAction.logout:
await AuthService.firebase().initialize();
if (!mounted) return;
final shouldLogOut = await showLogOutDialog(context);
if (shouldLogOut) {
await AuthService.firebase().logOut();
if (!mounted) return;
Navigator.of(context)
.pushNamedAndRemoveUntil(loginRoute, (_) => false);
}
break;
}
},
itemBuilder: (context) {
return [
const PopupMenuItem<MenuAction>(
value: MenuAction.logout,
child: Text(
'Log Out',
),
),
];
},
)
],
),
body: SingleChildScrollView(
child: Column(
children: [
Center(
child: ElevatedButton(
onPressed: () {
updateSwitchStatus();
},
child: Text(
switchState,
),
)),
Text(email),
Text(mID),
for (i = 1; i <= 9; i++)
Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
'Switch $i',
),
ElevatedButton(
onPressed: () {
updateListSwitchStaus();
},
child: Text(
listSwitchState,
),
),
],
),
),
],
),
),
);
}
void readUserData() async {
//UID of the user
final userID = FirebaseAuth.instance.currentUser!.uid;
//Database reference
DatabaseReference databaseReference =
FirebaseDatabase.instance.ref().child('Users/$userID');
final snapshot = await databaseReference.get();
if (snapshot.exists) {
setState(() {
email = snapshot.child('Email').value.toString();
mID = snapshot.child('Machine-ID').value.toString();
});
} else {
if (!mounted) return;
showErrorDialog(
context,
'Data not found',
);
}
databaseReference.onValue.listen((DatabaseEvent event) {
if (event.snapshot.exists) {
setState(() {
switchState = event.snapshot.child('Switch state').value.toString();
});
} else {
if (!mounted) return;
showErrorDialog(
context,
'Data not found',
);
}
});
}
void updateSwitchStatus() {
//UID of the user
final userID = FirebaseAuth.instance.currentUser!.uid;
DatabaseReference databaseReference =
FirebaseDatabase.instance.ref().child('Users/$userID');
if (switchState == 'ON') {
switchState = 'OFF';
databaseReference.update({'Switch state': switchState});
} else {
switchState = 'ON';
databaseReference.update({'Switch state': switchState});
}
}
void readListSwitchStatus() async {
//UID of the user
final userID = FirebaseAuth.instance.currentUser!.uid;
//Database reference
DatabaseReference databaseReference =
FirebaseDatabase.instance.ref().child('Users/$userID/Switches');
databaseReference.onValue.listen((event) async {
for (i = 1; i <= 9; i++) {
if (event.snapshot.exists) {
setState(() {
listSwitchState =
event.snapshot.child('Switch State $i').value.toString();
});
break;
} else {
setState(() {
listSwitchState = 'OFF';
});
databaseReference.child('Switch State $i').set(listSwitchState);
}
}
});
}
void updateListSwitchStaus() {
//UID of the user
final userID = FirebaseAuth.instance.currentUser!.uid;
//Database reference
DatabaseReference databaseReference =
FirebaseDatabase.instance.ref().child('Users/$userID/Switches');
for (i = 1; i <= 9; i++) {
if (listSwitchState == 'ON') {
listSwitchState = 'OFF';
databaseReference.update({'Switch state $i': listSwitchState});
} else {
listSwitchState = 'ON';
databaseReference.update({'Switch state $i': listSwitchState});
}
}
}
}
Future<bool> showLogOutDialog(BuildContext context) {
return showDialog<bool>(
context: context,
builder: (context) {
return AlertDialog(
title: const Text(
'Sign Out',
),
content: const Text(
'Are you sure you want to sign out?',
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(false);
},
child: const Text(
'Cancel',
),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: const Text(
'Yes',
),
)
],
);
}).then((value) => value ?? false);
}
Help me out!. Thanks in advance!

Flutter display server data / response from json

I have built a page which reads the json from recipeURL and I wish for it to display the product_name value in the json file. However for some reason my future fetchData () class isn't being read as none of the text in my if else statement is being displayed. Am I missing a simple oversight here?
EDIT: The main dart file is my main screen. This is where my navbar is created. Users are redirected to other pages when they click on the corresponding icon. Im having trouble passing BarcodePage(title:title); as parameters in my main file,26th line, can be found under Class MyAppState extends State<MyApp> {
My main dart file:
import 'package:flutter/material.dart';
import 'pages/BarcodePage.dart';
import 'pages/FoodPage.dart';
import 'pages/RecipePage.dart';
import 'pages/ShoppingPage.dart';
void main() {
runApp(MaterialApp(debugShowCheckedModeBanner: false, home: MyApp()),);
}
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState(){
return MyAppState();
}
}
class MyAppState extends State<MyApp> {
int _selectedPage =0;
final _pageOptions= [
FoodPage(),
RecipePage(),
BarcodePage(title: ,),
ShoppingPage(),
];
#override
Widget build(BuildContext context) {
return MaterialApp(
//title: 'Best B4',
theme: ThemeData(
primarySwatch: Colors.teal,),
debugShowCheckedModeBanner: false,
home: Scaffold (
appBar: AppBar(
title:Text(
'BestB4',
style: TextStyle(
fontFamily: 'PacificoRegular',
fontSize: 30,
),
),
backgroundColor: Colors.teal,
elevation: 20,
actions: [
IconButton(
icon: Icon(Icons.qr_code_2_rounded),
tooltip: 'Add item',
onPressed:(){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => BarcodePage()));
},
)
],
//ONPRESSED MENU OPEN
),
body:_pageOptions[_selectedPage],
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: Colors.teal,
selectedItemColor: Colors.white,
unselectedItemColor: Colors.white70,
iconSize: 40,
selectedFontSize: 15,
unselectedFontSize: 15,
currentIndex:_selectedPage,
onTap: (int index) {
setState(() {
_selectedPage = index;
});
},
items: [
BottomNavigationBarItem(
icon:Icon(Icons.restaurant_rounded),
label: 'Food',
), //, title:Text('Food')
BottomNavigationBarItem(
icon:Icon(Icons.menu_book_rounded),
label:'Recipes',
),//, title:Text('Recipes')
BottomNavigationBarItem(
icon:Icon(Icons.add_outlined),
label:'Add',
),//, title:Text('Add')
BottomNavigationBarItem(
icon:Icon(Icons.shopping_cart_rounded),
label:'Shopping',
),//,title:Text('Shopping')
],
),
),
);
}
}
My BarcodePage dart file:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as p;
import 'package:flutter/services.dart';
import 'package:barcode_scan2/barcode_scan2.dart';
import 'package:http/http.dart';
class BarcodePage extends StatefulWidget{
const BarcodePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_BarcodePageState createState() => _BarcodePageState();
}
var futuredata = {};
class _BarcodePageState extends State<BarcodePage> {
int counter=0;
String result= "";
Future _scanBarcode() async{
try{
ScanResult scanResult = await BarcodeScanner.scan();
String barcodeResult = scanResult.rawContent;
setState(() {
result = barcodeResult;
});
} on PlatformException catch (ex) {
if (ex.code == BarcodeScanner.cameraAccessDenied) {
setState((){
result = "CAMERA PERMISSION WAS DENIED. \n EDIT THIS IN YOUR SETTINGS";
});
}else {
setState(() {
result = "404 ERROR UNKNOWN $ex";
});
}
} on FormatException {
setState(() {
result = "SCAN AN ITEM";
});
} catch (ex){
setState(() {
result = "404 ERROR UNKNOWN $ex";
});
}
}
#override
void initState() {}
fetchmydata() async {
var request = p.Request(
'GET',
Uri.parse(
'https://world.openfoodfacts.org/api/v0/product/5060391623139.json'));
StreamedResponse response = await request.send();
if (response.statusCode == 200) {
// print(await response.stream.bytesToString());
var data = await response.stream.bytesToString();
futuredata = json.decode(data);
} else {
print(response.reasonPhrase);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.teal,
title:Text('Add an item',
style: TextStyle(
fontFamily: 'Fredoka',
fontSize: 25,
),
),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
FutureBuilder(
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return Center(
child: Container(
child: CircularProgressIndicator(),
height: 50,
width: 50,
),
);
else if (snapshot.connectionState == ConnectionState.done)
return ListTile(
title: Text(futuredata["product"]["product_name"].toString()),
subtitle: Text("France:" +
futuredata["product"]["product_name_en"].toString()),
);
else {
return Container(
child: CircularProgressIndicator(),
height: 50,
width: 50,
);
}
},
future: fetchmydata(),
)
],
),
floatingActionButton: FloatingActionButton.extended(
backgroundColor: Color.fromRGBO(51, 171, 160, 100),
icon: Icon(Icons.camera_alt),
label: Text("Scan"),
onPressed: _scanBarcode,
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
);
}
}
The Json file looks like this:
JSON LINK: https://world.openfoodfacts.org/api/v0/product/5060391623139.json
You can read your json like this
var futuredata = {};
var productname= futuredata["product"]["product_name"]
Your fetch method like this
fetchmydata() async {
var request = p.Request(
'GET',
Uri.parse(
'https://world.openfoodfacts.org/api/v0/product/5060391623139.json'));
StreamedResponse response = await request.send();
if (response.statusCode == 200) {
// print(await response.stream.bytesToString());
var data = await response.stream.bytesToString();
futuredata = json.decode(data);
} else {
print(response.reasonPhrase);
}
}
With model Class
SampleModel? Mymodel = null;
fetchmydata() async {
var request = p.Request(
'GET',
Uri.parse(
'https://world.openfoodfacts.org/api/v0/product/5060391623139.json'));
StreamedResponse response = await request.send();
if (response.statusCode == 200) {
// print(await response.stream.bytesToString());
var data = await response.stream.bytesToString();
futuredata = json.decode(data);
Mymodel = SampleModel.fromJson(futuredata);
} else {
print(response.reasonPhrase);
}
}
in the method we first read data from json as string or text
then we decode the string type or text from server to map type
SampleCode Dartpad live code check
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:http/http.dart' as p;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
var futuredata = {};
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
#override
void initState() {}
fetchmydata() async {
var request = p.Request(
'GET',
Uri.parse(
'https://world.openfoodfacts.org/api/v0/product/5060391623139.json'));
StreamedResponse response = await request.send();
if (response.statusCode == 200) {
// print(await response.stream.bytesToString());
var data = await response.stream.bytesToString();
futuredata = json.decode(data);
} else {
print(response.reasonPhrase);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
FutureBuilder(
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return Center(
child: Container(
child: CircularProgressIndicator(),
height: 50,
width: 50,
),
);
else if (snapshot.connectionState == ConnectionState.done)
return ListTile(
title: Text(futuredata["product"]["product_name"].toString()),
subtitle: Text("France:" +
futuredata["product"]["product_name_en"].toString()),
);
else {
return Container(
child: CircularProgressIndicator(),
height: 50,
width: 50,
);
}
},
future: fetchmydata(),
)
],
),
);
}
}
Sample ModelClass
///
/// Code generated by jsonToDartModel https://ashamp.github.io/jsonToDartModel/
///
class SampleModelProduct {
/*
{
"_id": "5060391623139",
"_keywords": [
"peanut"
],
"product_name": "Peanut butter",
"product_name_en": "Peanut butter",
"product_name_fr": "Peanut butter"
}
*/
String? Id;
List<String?>? Keywords;
String? productName;
String? productNameEn;
String? productNameFr;
SampleModelProduct({
this.Id,
this.Keywords,
this.productName,
this.productNameEn,
this.productNameFr,
});
SampleModelProduct.fromJson(Map<String, dynamic> json) {
Id = json['_id']?.toString();
if (json['_keywords'] != null) {
final v = json['_keywords'];
final arr0 = <String>[];
v.forEach((v) {
arr0.add(v.toString());
});
Keywords = arr0;
}
productName = json['product_name']?.toString();
productNameEn = json['product_name_en']?.toString();
productNameFr = json['product_name_fr']?.toString();
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['_id'] = Id;
if (Keywords != null) {
final v = Keywords;
final arr0 = [];
v!.forEach((v) {
arr0.add(v);
});
data['_keywords'] = arr0;
}
data['product_name'] = productName;
data['product_name_en'] = productNameEn;
data['product_name_fr'] = productNameFr;
return data;
}
}
class SampleModel {
/*
{
"code": "5060391623139",
"product": {
"_id": "5060391623139",
"_keywords": [
"peanut"
],
"product_name": "Peanut butter",
"product_name_en": "Peanut butter",
"product_name_fr": "Peanut butter"
},
"status": 1,
"status_verbose": "product found"
}
*/
String? code;
SampleModelProduct? product;
int? status;
String? statusVerbose;
SampleModel({
this.code,
this.product,
this.status,
this.statusVerbose,
});
SampleModel.fromJson(Map<String, dynamic> json) {
code = json['code']?.toString();
product = (json['product'] != null)
? SampleModelProduct.fromJson(json['product'])
: null;
status = json['status']?.toInt();
statusVerbose = json['status_verbose']?.toString();
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['code'] = code;
if (product != null) {
data['product'] = product!.toJson();
}
data['status'] = status;
data['status_verbose'] = statusVerbose;
return data;
}
}
try creating a .g.dart file using flutter packages pub run build_runner build. flutter automatically will create your binding class factory. once you have the binding classes created flutter will automatically code your binding class, including nested classes. I personally think automation is the way to handle all interactions with json from the server. The reason you want to use the future .g.dart code generator is to reduce the possibility of error and incorrect type casting.
file.dart
factory ProductView.fromJson(Map<String, dynamic> json) =>
_$ProductFromJson(json);
Map<String, dynamic> toJson() => _$ProductViewToJson(this);
file.g.dart
ProductView _$ProductViewFromJson(Map<String, dynamic> json) {
return
ProductView(
json['field1'] as int,
json['field2'] as String,
json['field3'] == null
? null
: DateTime.parse(json['field3'] as String),
);
}
Map<String, dynamic> _$ProjectViewToJson(ProductView instance) =>
<String, dynamic>{
'field1': instance.field1,
'field2': instance.field2,
'field3': instance.field3?.toIso8601String(),
};
decoding the json
var client = http.Client();
Map<String, String> headers = new HashMap();
headers['Accept'] = 'application/json';
headers['Content-Type'] = 'application/json';
headers['Authorization'] = 'Bearer $token';
var response = await client.get(url, headers: headers).timeout(_TIMEOUT);
var parsed = json.decode(response.body);
var view = ProductView.fromJson(parsed);

The named parameter 'fileExtension' is not defined

I am using some code from an older version of File Picker, the null safety version will mess up my other code so I'm using 1.1.1.
the code isn't incorrect because it the same on the file picker package example. can anyone help plz?
the code goes as followed
void openFileExplorer() async {
try {
_path = null;
if (_multiPick) {
_paths = await FilePicker.getMultiFilePath(
type: _pickType, **fileExtension**: _extension);
} else {
_path = await FilePicker.getFilePath(
type: _pickType, **fileExtension**: _extension);
}
uploadToFirebase();
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
}
if (!mounted) return;
}
Try this one
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: UploadMultipleImageDemo(),
);
}
}
class UploadMultipleImageDemo extends StatefulWidget {
UploadMultipleImageDemo() : super();
final String title = 'Firebase Storage';
#override
UploadMultipleImageDemoState createState() => UploadMultipleImageDemoState();
}
class UploadMultipleImageDemoState extends State<UploadMultipleImageDemo> {
//
String _path;
Map<String, String> _paths;
List<String> extensions;
FileType _pickType;
bool _multiPick = false;
GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();
List<StorageUploadTask> _tasks = <StorageUploadTask>[];
void openFileExplorer() async {
try {
_path = null;
if (_multiPick) {
_paths = await FilePicker.getMultiFilePath(
type: _pickType, allowedExtensions: extensions);
} else {
_path = await FilePicker.getFilePath(
type: _pickType, allowedExtensions: extensions);
}
//uploadToFirebase();
} on PlatformException catch (e) {
print("Unsupported operation" + e.toString());
}
if (!mounted) return;
}
// uploadToFirebase() {
// if (_multiPick) {
// _paths.forEach((fileName, filePath) => {upload(fileName, filePath)});
// } else {
// if (_path != null) {
// String fileName = _path
// .split('/')
// .last;
// String filePath = _path;
// upload(fileName, filePath);
// }
// }
// }
// upload(fileName, filePath) {
// extensions = fileName.toString().split('.').last as List<String>;
// StorageReference storageRef =
// FirebaseStorage.instance.ref().child(fileName);
// final StorageUploadTask uploadTask = storageRef.putFile(
// File(filePath),
// StorageMetadata(
// contentType: '$_pickType/$extensions',
// ),
// );
// setState(() {
// _tasks.add(uploadTask);
// });
// extensions = null;
// }
dropDown() {
return DropdownButton(
hint: new Text('Select'),
value: _pickType,
items: <DropdownMenuItem>[
new DropdownMenuItem(
child: new Text('Audio'),
value: FileType.audio,
),
new DropdownMenuItem(
child: new Text('Image'),
value: FileType.image,
),
new DropdownMenuItem(
child: new Text('Video'),
value: FileType.video,
),
new DropdownMenuItem(
child: new Text('Any'),
value: FileType.any,
),
],
onChanged: (value) => setState(() {
_pickType = value;
}),
);
}
String _bytesTransferred(StorageTaskSnapshot snapshot) {
return '${snapshot.bytesTransferred}/${snapshot.totalByteCount}';
}
#override
Widget build(BuildContext context) {
final List<Widget> children = <Widget>[];
_tasks.forEach((StorageUploadTask task) {
final Widget tile = UploadTaskListTile(
task: task,
onDismissed: () => setState(() => _tasks.remove(task)),
onDownload: () => downloadFile(task.lastSnapshot.ref),
);
children.add(tile);
});
return new MaterialApp(
home: new Scaffold(
key: _scaffoldKey,
appBar: new AppBar(
title: Text(widget.title),
),
body: new Container(
padding: EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
dropDown(),
SwitchListTile.adaptive(
title: Text('Pick multiple files', textAlign: TextAlign.left),
onChanged: (bool value) => setState(() => _multiPick = value),
value: _multiPick,
),
OutlineButton(
onPressed: () => openFileExplorer(),
child: new Text("Open file picker"),
),
SizedBox(
height: 20.0,
),
Flexible(
child: ListView(
children: children,
),
),
],
),
),
),
);
}
Future<void> downloadFile(StorageReference ref) async {
final String url = await ref.getDownloadURL();
final http.Response downloadData = await http.get(url);
final Directory systemTempDir = Directory.systemTemp;
final File tempFile = File('${systemTempDir.path}/tmp.jpg');
if (tempFile.existsSync()) {
await tempFile.delete();
}
await tempFile.create();
final StorageFileDownloadTask task = ref.writeToFile(tempFile);
final int byteCount = (await task.future).totalByteCount;
var bodyBytes = downloadData.bodyBytes;
final String name = await ref.getName();
final String path = await ref.getPath();
print(
'Success!\nDownloaded $name \nUrl: $url'
'\npath: $path \nBytes Count :: $byteCount',
);
_scaffoldKey.currentState.showSnackBar(
SnackBar(
backgroundColor: Colors.white,
content: Image.memory(
bodyBytes,
fit: BoxFit.fill,
),
),
);
}
}
class UploadTaskListTile extends StatelessWidget {
const UploadTaskListTile(
{Key key, this.task, this.onDismissed, this.onDownload})
: super(key: key);
final StorageUploadTask task;
final VoidCallback onDismissed;
final VoidCallback onDownload;
String get status {
String result;
if (task.isComplete) {
if (task.isSuccessful) {
result = 'Complete';
} else if (task.isCanceled) {
result = 'Canceled';
} else {
result = 'Failed ERROR: ${task.lastSnapshot.error}';
}
} else if (task.isInProgress) {
result = 'Uploading';
} else if (task.isPaused) {
result = 'Paused';
}
return result;
}
String _bytesTransferred(StorageTaskSnapshot snapshot) {
return '${snapshot.bytesTransferred}/${snapshot.totalByteCount}';
}
#override
Widget build(BuildContext context) {
return StreamBuilder<StorageTaskEvent>(
stream: task.events,
builder: (BuildContext context,
AsyncSnapshot<StorageTaskEvent> asyncSnapshot) {
Widget subtitle;
if (asyncSnapshot.hasData) {
final StorageTaskEvent event = asyncSnapshot.data;
final StorageTaskSnapshot snapshot = event.snapshot;
subtitle = Text('$status: ${_bytesTransferred(snapshot)} bytes sent');
} else {
subtitle = const Text('Starting...');
}
return Dismissible(
key: Key(task.hashCode.toString()),
onDismissed: (_) => onDismissed(),
child: ListTile(
title: Text('Upload Task #${task.hashCode}'),
subtitle: subtitle,
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Offstage(
offstage: !task.isInProgress,
child: IconButton(
icon: const Icon(Icons.pause),
onPressed: () => task.pause(),
),
),
Offstage(
offstage: !task.isPaused,
child: IconButton(
icon: const Icon(Icons.file_upload),
onPressed: () => task.resume(),
),
),
Offstage(
offstage: task.isComplete,
child: IconButton(
icon: const Icon(Icons.cancel),
onPressed: () => task.cancel(),
),
),
Offstage(
offstage: !(task.isComplete && task.isSuccessful),
child: IconButton(
icon: const Icon(Icons.file_download),
onPressed: onDownload,
),
),
],
),
),
);
},
);
}
}

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 send dynamic url from DataProvider to PDF Flutter

I'm new to Flutter. I have DataProvider which consists of Pdf data like it's Title, pdfURL and etc and I created a ListView on that ListView I have some items.
Whenever I click on any item it should open specified pdf url on PDF VIEWER. I want to pass that data dynamically to the getFileFromUrl; how should I pass that data.
This is my DataProvider class:
class DataProvider with ChangeNotifier{
List<PdfBook> _pdfItems = [
PdfBook(
id: 'p1',
title: 'PDF Bookmark Sample',
pdfUrl: 'https://www.adobe.com/support/products/enterprise/knowledgecenter/media/c4611_sample_explain.pdf',
avatar: 'T',
),
PdfBook(
id: 'p2',
title: 'PDF 995',
pdfUrl: 'http://www.pdf995.com/samples/pdf.pdf',
avatar: 'T2',
),
];
List<PdfBook> get pdfItems{
return [..._pdfItems];
}
PdfBook findById(String id){
return _pdfItems.firstWhere((item) => item.id == id);
}
}
This is my PdfViewState:
class PdfItem extends StatefulWidget {
#override
_PdfItemState createState() => _PdfItemState();
}
class _PdfItemState extends State<PdfItem> {
String assetPDFPath = "";
String urlPDFPath = "";
#override
void initState() {
super.initState();
getFileFromAsset("assets/mypdf.pdf").then((f) {
setState(() {
assetPDFPath = f.path;
print(assetPDFPath);
});
});
getFileFromUrl("http://www.pdf995.com/samples/pdf.pdf").then((f) {
setState(() {
urlPDFPath = f.path;
print(urlPDFPath);
});
});
}
Future<File> getFileFromAsset(String asset) async {
try {
var data = await rootBundle.load(asset);
var bytes = data.buffer.asUint8List();
var dir = await getApplicationDocumentsDirectory();
File file = File("${dir.path}/mypdf.pdf");
File assetFile = await file.writeAsBytes(bytes);
return assetFile;
} catch (e) {
throw Exception("Error opening asset file");
}
}
Future<File> getFileFromUrl(String url) async {
try {
var data = await http.get(url);
var bytes = data.bodyBytes;
var dir = await getApplicationDocumentsDirectory();
File file = File("${dir.path}/mypdfonline.pdf");
File urlFile = await file.writeAsBytes(bytes);
return urlFile;
} catch (e) {
throw Exception("Error opening url file");
}
}
#override
Widget build(BuildContext context) {
final pdf = Provider.of<PdfBook>(context, listen: false);
return ListTile(
title: Text(pdf.title),
onTap: () {
if (urlPDFPath != null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
PdfViewPage(path: urlPDFPath)));
}
},
leading: CircleAvatar(
child: Text(pdf.avatar),
backgroundColor: Theme.of(context).accentColor,
),
trailing: Icon(Icons.arrow_right),
);
}
}
This is my ListView Class:
class PdfListView extends StatelessWidget {
#override
Widget build(BuildContext context) {
final pdfData = Provider.of<DataProvider>(context);
final pdf = pdfData.pdfItems;
return Scaffold(
appBar: AppBar(
title: Text("PDF Books"),
),
body: ListView.builder(
itemCount: pdf.length,
itemBuilder: (ctx, i) => ChangeNotifierProvider.value(
value: pdf[i],
child: PdfItem(),
),
),
);
}
}