Flutter 1.0 - Unable to load text asset - flutter

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.

Related

Flutter audioplayers: ^2.0.0 error Unhandled Exception: Unable to load asset: assets//data/user/0/com.xxxx.xxxx/cache/flip.mp3

I'm trying to use audioplayers: ^2.0.0,but i got this error, how to solve it?please!
pubspec.yaml
flutter:
uses-material-design: true
assets:
- assets/audio/
Code
Future setAudio() async {
AudioPlayer audioPlayer = AudioPlayer();
audioPlayer.setReleaseMode(ReleaseMode.loop);
AudioCache audioCache = AudioCache(prefix: 'assets/audio/');
final url = await audioCache.load('flip.mp3');
audioPlayer.setSourceAsset(url.path);
}
You shouldn't use the full path in setSourceAsset, and since you've already set a prefix for the cache you kust have to write the filename:
audioPlayer.setSourceAsset('flip.mp3');

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.

app database generated file having errors in moor flutter

I am using moor package in flutter for my application. im following the instructions online
https://moor.simonbinder.eu/docs/getting-started/starting_with_sql/#what-moor-generates
but when i run the build command: flutter pub run build_runner build
the appdatabase.g.dart file that gets generated has errors. here is a snapshot of errors:
here is my dependencies
cupertino_icons: ^0.1.2
month_picker_dialog: ^0.3.1
flutter_cupertino_localizations: ^1.0.1
moor: ^2.3.0
provider: ^4.0.3
moor_ffi: ^0.4.0
path_provider: ^1.6.0
dev_dependencies:
flutter_test:
sdk: flutter
intl_translation: ^0.17.1
moor_generator: ^2.3.1
build_runner:
the problem seems to be with 'Table' class. there is a conflict between dart and moor. the message indicate there are two versions. how can i solve this problem so that my error goes away
the answer is to use import 'package:flutter/widgets.dart' hide Table;
dependencies:
flutter:
sdk: flutter
#moor database
moor_flutter: ^3.1.0
# For the UI
provider: ^4.3.1
# For OS-specific directory paths
path_provider: ^1.6.11
cupertino_icons: ^0.1.3
dev_dependencies:
flutter_test:
sdk: flutter
#new Dependencies add
moor_generator: ^3.2.0
build_runner:
Step 1 : delete file appdatabase.g.dart
step 2: flutter clean
Step 3: flutter pub get
Step 4: flutter pub run build_runner build watch
This error occurs when you don't have the 'import' of your table or dao in your AppDb class, in my case I have more than 90 tables and dao's, I separated then in a class with a static list, but I need do the imports of my files in the app_database.dart too, because of the error.
I have this class for tables:
import '../tables/table_one.dart';
import '../tables/table_two.dart';
class TableList {
static const List<Type> tables = [
TableOne,
TableTwo,
]
}
And another for Dao files:
import '../dao/table_one_dao.dart';
import '../dao/table_two_dao.dart';
class DaoList{
static const List<Type> daos= [
TableOne,
TableTwo,
]
}
And this is my AppDb class:
import '../tables/table_one.dart';
import '../tables/table_two.dart';
import '../dao/table_one_dao.dart';
import '../dao/table_two_dao.dart';
part 'app_db.g.dart';
#DriftDatabase(
tables: TableList.tables,
daos: DaoList.daos,
)
class AppDb extends _$AppDb {
AppDb() : super(_openConnection());
#override
int get schemaVersion => 1;
}
LazyDatabase _openConnection() {
return LazyDatabase(() async {
final dbFolder = await getApplicationDocumentsDirectory();
final file = File(p.join(dbFolder.path, 'app_database.db'));
return NativeDatabase(file);
});
}
As you see, i have to declare the imports again in my AppDb file to resolve. If you declare your tables directly in the AppDb escope, i think you don't have problem.

FlutterError (Unable to load asset: assets/chat1 .txt)

I know I placed my text file at the location assets\chat1.txt, and my code also works with other txts but somehow I always get the following error:
Exception has occurred.
FlutterError (Unable to load asset: assets/chat1.txt)
my Code:
Future<String> getFileData(String path) async {
return await rootBundle.loadString(path);
}
pubspec.yaml
flutter:
assets:
- assets/
Add the full path in pubspec.yaml file and you should consider the indentation for assets:
flutter:
assets:
- assets/chat1.txt

Flutter play custom sound using audioplayers 0.7.7?

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')