Load different json files in flutter - flutter

I have 3 local json files that are similar. I want to load each of them at different times in flutter. Is there anyway to pass variables in future for doing this?

You can load anything that is included as an Asset in your app. So for example, you could put this in your pubspec.yaml:
assets:
- config/ordinary.json
- config/special.json
Then you could load either of those in your code, like this:
final config = await DefaultAssetBundle
.of(context)
.loadString('config/ordinary.json');

Related

camera_windows save picture to different directory

I am using the flutter package camera_windows using the exact sample code listed here
camera_windows
It looks like by default it saves it to the "Pictures" directory in windows but I was wondering how do I save it to a different directory with a different filename also it looks like I cant pass a "path" to the call of the function for example
final XFile file = await CameraPlatform.instance.takePicture(_cameraId);
_showInSnackBar('Picture captured to: ${file.path}');

How can I get a list of filepaths from the project assets in Flutter?

I have added a bunch of Images to my App's resources folder and I want to list all of the Images from my icons folder, so the user can pick which one they want to use for their listelement.
My Folder is included in the Pubspec.yaml and I can call AssetImage("/res/assets/icons/") and it gets the image I want manually.
I want to store the path later to call AssetImage(path) on it.
But when I call List files = Directory("/res/assets/icons/").listSync();, I get this exception:
What do I need to do to get all the file paths from the files in my directory?
you can list all the images in your specific directory like this:
final images = json.decode(await rootBundle.loadString('AssetManifest.json')).keys
.where((String key) => key.contains('res/assets/icons/'))
.toList();
print(images.toString());

How to get a list of all cached audio?

For example, my podcast app has a list of all downloaded podcast, how do I get a list of all LockCachingAudioSource that has been downloaded using request() method?
When you create your LockCachingAudioSource instances, you can choose the location where you want them to be saved. If you create a directory for that purpose, you can obtain a directory listing using Dart's file I/O API. The directory listing will also show partially downloaded files and other temporary files, which you want to ignore. These have extensions .mime and .part.
Having explained that, here is a solution. First, create your cache directory during app init:
final cacheDir = File('/your/choice/of/location');
...
await cacheDir.create(recursive: true);
Then for each audio source, create it like this:
import 'package:path/path.dart' as p;
...
source = LockCachingAudioSource(
uri,
cacheFile: File(p.joinAll([cacheDir, 'yourChoiceOfName.mp3'],
);
Now you can get a list of downloaded files at any time by listing the cacheDir and ignoring any temporary files:
final downloadedFiles = (await _getCacheDir()).list().where((f) =>
!['mime', 'part'].contains(f.path.replaceAll(RegExp(r'^.*\.'), '')));
If you need to turn these files back into the original URI, you could either create your own database to store which file is for which URI, or you choose the file name of each of your cache files by encoding the URI in base64 or something that's reversable, so given a file name, you can then decode it back into the original URI.

How to delete all the boxes in Hive Flutter?

I am developing an application using Flutter; it will store some data locally, so I decided to use Hive package which was really amazing package to store data. So now I will store all the data locally when the user press the sync button. After that, if the user clicks sync again, I have to delete all the boxes and store data which may or may not have the same box name.
I don't want to increase the application storage to increase if the sync button is clicked, I want to delete all the boxes and again I want to create the box.
You can use deleteFromDisk method. It removes the file which contains the box and closes the box.
_myCourseBox.deleteFromDisk();
Unfortunately, I don't think a feature to clear() all (opened, plus unopened) Hive boxes has been implemented. The box files are basically thrown into your device's application document directory as *.hive files (with compacted files as *.hivec and lock files as *.lock). There's no separate key-value store (or Hive box) that keeps track of previously created boxes, though you can implement such a Hive box yourself and iterate over those values as you please.
In your case, where you simply want to delete all the boxes in one sweep, a workaround could be to place all Hive boxes into a sub-directory (using Hive.initFlutter('chosenPath') ) and simply delete the directory when necessary using standard file operations. The only gotcha being that you call Hive.close() to close all open boxes before attempting this (to delete the undeletable *.lock files).
To simplify cross-platform references to the app's document directory you can use the path_provider package. Add path_provider: ^1.6.5 to your dependencies in pubspec.yaml, and where necessary in your dart application import 'package:path_provider/path_provider.dart'; and import 'dart:io'; for file operations;
Let's say you use Hive.initFlutter('chosenPath') to initialise and store your Hive.
So whenever you want to clear all boxes (after ensuring Hive.close() has been called), you could use the following code:
// Get the application's document directory
var appDir = await getApplicationDocumentsDirectory();
// Get the chosen sub-directory for Hive files
var hiveDb = Directory('${appDir.path}/chosenPath');
// Delete the Hive directory and all its files
hiveDb.delete(recursive: true);
The directory will be re-generated from scratch the next time you call Hive.initFlutter('chosenPath').
You didn't share any code so I will just give an example.
I would suggest you to open the boxes in your main function
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Hive.initFlutter();
Hive.registerAdapter(yourAdapter());
await Hive.openBox('yourBoxName');
}
When user wants to sync, you can do following;
// It will delete all the entry in the box
Hive.box('yourBoxName').clear();
yourSyncOperation();

Flutter: How to get a File object from ImageProvider in Flutter?

How can I get a File from an ImageProvider?
ImageProvider imageProvider = NetworkImage(networkUrl);
File file = imageProvider ?
Although ImageProvider with NetworkImage renders the content of your network image URL, it doesn't have direct APIs or easy way for you to be able to convert it to a File object. With that said, you can still manually cache (or download) the image/s and get the download stream.
As far as I can understand your question, you are trying to access the network image URL as a File object. Instead of using ImageProvider, you can take a look at the flutter_cache_manager, which is a plugin used for downloading and caching files locally, and save it for later use.
Example Usage
Downloading network image file from URL
await DefaultCacheManager().downloadFile(url);
Retrieving File object from the cache dir
// Retrieving File object
var file = await DefaultCacheManager().getSingleFile(imageUrl);
// File object available for use
// Eg. Reading file as string
file.readAsStringSync(...);
Further reading
https://pub.dev/packages/flutter_cache_manager
https://pub.dev/packages/cached_network_image