Flutter play custom sound using audioplayers 0.7.7? - flutter

pubspec.yaml
flutter:
uses-material-design: true
assets:
- assets/Images/1.png
- assets/Images/MP3.mp3
Test.dart
Widget localAsset() {
return _tab([
Text("Click to play"),
_btn('Play', () => audioCache.play('assets\Images\MP3.mp3')),
]);
}
I am new to flutter, for my applications i want play two sounds mode(background sound ,button action sound), after referred from flutter package i have changed code like as above , when i used this widget in my material,i am getting below error,
E/flutter ( 2750): [ERROR:flutter/shell/common/shell.cc(181)] Dart Error: Unhandled exception:
E/flutter ( 2750): Unable to load asset: assets/assetsImagesMP3.mp3
E/flutter ( 2750): #0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)

Backslash are Windows-specific. Use slashes instead. Android is Unix-based and so is iOS
audioCache.play('assets/Images/MP3.mp3')

Related

I am using pdf lib to generate pdf and I want to add a simple text to pdf coming from the API, the text can be very long like 3,4 pages or more

I am using pdf lib to generate pdf and I want to add a text in pdf coming from the API, the text can be very long like 3,4 pages or more. Below is my code.
List<pw.Widget> widgets = [];
widgets.add(pw.Text(provider.getExtractedText));
final pdf = pw.Document();
pdf.addPage(
pw.MultiPage(
build: (pw.Context context) {
return [
pw.Wrap(
children: widgets
)
];
},
),
);
but i am getting the following exception.
E/flutter (19405): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Exception: This widget created more than 20 pages. This may be an issue in the widget or the document. See https://pub.dev/documentation/pdf/latest/widgets/MultiPage-class.html
E/flutter (19405): #0 MultiPage.generate.<anonymous closure> (package:pdf/src/widgets/multi_page.dart:251:11)
E/flutter (19405): #1 MultiPage.generate (package:pdf/src/widgets/multi_page.dart:255:8)
E/flutter (19405): #2 Document.addPage (package:pdf/src/widgets/document.dart:118:10)
E/flutter (19405): #3 _DocumentConversionScreenState.saveFile (package:speak_and_translate/screens/document_conversion_screen.dart:215:11)
E/flutter (19405): <asynchronous suspension>
E/flutter (19405):
Your stacktrace gives you file and line number - so go and look there:
// Detect too big widgets
if (sameCount++ > maxPages) {
throw Exception(
'This widget created more than $maxPages pages. This may be an issue in the widget or the document. See https://pub.dev/documentation/pdf/latest/widgets/MultiPage-class.html');
}
As you see, it compares to maxPages. Where is that set? Check line 152:
this.maxPages = 20,
So, change that default to a sensible number for your application:
pw.MultiPage(
maxPages: 40, // <- add max pages here
build: (pw.Context context) {

Flutter : image not being found [duplicate]

This question already has answers here:
How to add image in Flutter
(15 answers)
Closed 1 year ago.
This is my widget to display a little pic of myself in the app.
Widget image() {
return CircleAvatar(
radius: 50.0,
backgroundImage: AssetImage('images/me.jpeg'),
);
}
Yet, for some reason, I keep getting this
The following assertion was thrown resolving an image codec:
Unable to load asset: images/me.jpeg
When the exception was thrown, this was the stack:
#0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:225:7)
<asynchronous suspension>
#1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:668:31)
#2 AssetBundleImageProvider.load (package:flutter/src/painting/image_provider.dart:651:14)
#3 ImageProvider.resolveStreamForKey.<anonymous closure> (package:flutter/src/painting/image_provider.dart:504:13)
...
Image provider: AssetImage(bundle: null, name: "images/me.jpeg")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#14309(), name: "images/me.jpeg", scale: 1.0)
Although the image is inside the folder. Please help
make sure you added the images to pubspec.yaml file and then run pub get
assets:
- images/me.jpeg

How to use Image.file widget in flutter

'''
I/flutter ( 7954): The following FileSystemException was thrown resolving an image codec:
I/flutter ( 7954): Cannot open file, path = 'image.png' (OS Error: No such file or directory, errno = 2)
I/flutter ( 7954):
I/flutter ( 7954): When the exception was thrown, this was the stack:
I/flutter ( 7954): #0 _File.open.<anonymous closure> (dart:io/file_impl.dart:366:9)
I/flutter ( 7954): (elided 13 frames from dart:async)
I/flutter ( 7954): ...
I/flutter ( 7954):
I/flutter ( 7954): Path: image.png
I/flutter ( 7954): ════════════════════════════════════════════════════════════════════════════════════════════════════
I am using image.file to display the widget but it throws the below exception how to solve that and I add my code as image.what is the major difference between image.asset widget and image.file widget.Thanks in advance.
You need to add the correct location of the file:
File file = new File('directoryLocation/image.png');
Another way to load images, is to add them to the assets folder in the project, then in the pubspec.yaml, you can do the following:
flutter:
assets:
- assets/my_icon.png
- assets/background.png
Then do:
Widget build(BuildContext context) {
return Image(image: AssetImage('assets/my_icon.png'));
}
Check the docs:
https://flutter.dev/docs/development/ui/assets-and-images
Image.asset is used to load images from your projects assets folder. As because its already available in the project and pretty straight foreword to use.
Image.asset('assets/image.jpg');
On the other hand Image.file is used to load images from devices internal/external storage. This way you have to locate the image using ImagePicker or any other library to get the path of the image. Using this path create a File object and provide it to Image.file.
String path = 'your/image/path/here';
File imageFile = File(path);
Widget image = Image.file(imageFile);

Hosting an executable within a Flutter application

I have a basic flutter project running on android where when the application starts, I write an executable bundled in my assets.
static String appInternalPath = '/data/data/com.maksimdan.face_merger';
void writeExecutable() async {
var executablePath = join(appInternalPath, 'main');
if (await File(executablePath).exists()) {
File(executablePath).delete();
print('deleted old executable');
} else {
print('not executable exists');
}
ByteData data = await rootBundle.load('lib/py/dist/main');
List<int> bytes =
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(executablePath).writeAsBytes(bytes);
print('wrote new executable');
}
Sometime later in my code I try to run it.
void invokeExecutable() async {
String executablePath = join(appInternalPath, 'main');
Process.run('chmod', ['u+x', executablePath]).then((ProcessResult results) {
Process.run(executablePath, []).then((ProcessResult results) {
print(results.stdout);
});
});
}
But obtain a permission denied error.
E/flutter (31825): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: ProcessException: Permission denied
E/flutter (31825): Command: /data/data/com.maksimdan.flutter_general/main
E/flutter (31825): #0 _ProcessImpl._start (dart:io-patch/process_patch.dart:390:33)
E/flutter (31825): #1 Process.start (dart:io-patch/process_patch.dart:36:20)
E/flutter (31825): #2 _runNonInteractiveProcess (dart:io-patch/process_patch.dart:565:18)
E/flutter (31825): #3 Process.run (dart:io-patch/process_patch.dart:47:12)
E/flutter (31825): #4 _MyHomePageState.invokeExecutable.<anonymous closure> (package:flutter_general/main.dart:51:15)
E/flutter (31825): #5 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (31825): #6 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (31825): <asynchronous suspension>
I've also tried:
Process.run('/system/bin/chmod', ['744', path]).then((ProcessResult results) {
print('shell1 complete');
Process.run(path, []).then((ProcessResult results) {
print('shell2 complete');
print(results.stdout);
});
});
My executable:
// 'Hello World!' program
#include <iostream>
int main()
{
std::cout << "Hello World!" << std::endl;
return 0;
}
>> g++ main.cc -o main
Is there a way to run your own executables in flutter with the proper permissions? On native android, there is an option to file.setExecutable(true); using this strategy. (Hosting an executable within Android application)
Or will I have to experiment with method channels?
pubspec.yml
name: face_merger
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
sqflite: ^1.3.0+2
process_run: ^0.10.10+1
cupertino_icons: ^0.1.3
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- lib/py/dist/main
I also verified that the file was written to the internal memory of on the device that I expected it to be written to using android studio's device explore.
Besides the writable permission you need to have readable permission in your app.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xxx.yyy">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
...
You need to put the .db file extension at the end of the database name (Assuming DB_DIR is for a database). var path = join(DB_DIR, 'main.db');
Then I think you may want to use path_provider package and use
Directory documentsDirectory = await getApplicationDocumentsDirectory();
for the directory where you are accessing the database.

Flutter 1.0 - Unable to load text asset

I'm having some trouble loading text assets in flutter (1.0).
This is the current code attempting to read the asset.
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<String> getFileData(String path) async {
return await rootBundle.loadString(path);
}
Future<File> get _localFile async {
final path = await _localPath;
final file = File('$path/toon_test_3.json');
bool exists = file.existsSync();
if(exists){
return file;
} else {
// Load the default file
final newfile = await getFileData('toonRepo/data.json');
return file.writeAsString(newfile);
}
}
loadString will failing popping up the following:
Could not load source 'dart:core/runtime/libobject_patch.dart': <source not available>.
If execution continues the following exception is raised:
Exception has occurred.
FlutterError (Unable to load asset: toonRepo/data.json)
I've tried a lot of solutions here that revolve around the asset section in pubspec.yaml
name: hello_world
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ">=2.0.0-dev.68.0 <3.0.0"
dependencies:
path_provider: ^0.4.1
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
english_words: ^3.1.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
assets:
- toonRepo/
uses-material-design: true
Am I going wrong somewhere very silly?
Cheers for any pointers you have.
Project Structure
Here is a temporary copy of the code if you want to take a peek.
Github
And here's a stack trace
[VERBOSE-2:shell.cc(184)] Dart Error: Unhandled exception:
Unable to load asset: toonRepo/data.json
#0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
<asynchronous suspension>
#1 AssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:67:33)
<asynchronous suspension>
#2 CachingAssetBundle.loadString.<anonymous closure> (package:flutter/src/services/asset_bundle.dart:162:56)
#3 __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.putIfAbsent (dart:collection/runtime/libcompact_hash.dart:284:23)
The asset access works fine with the pubspec.yaml in your question.
new Text("Name: " + toon.info.name)),
fails because toon is null because it never got a value assigned.
You could use new Text("Name: " + (toon?.info?.name ?? 'foo')), to work around the exception.
If you add
widget.storage.getFileData('toonRepo/data.json').then((f) => print(f));
to _FlutterDemoState.initState(), you'll see that reading the asset works just fine.