i have read https://flutter.dev/docs/development/ui/assets-and-images#asset-images-in-package-dependencies and Flutter - Read text file from assets and applied all there was but my code still doesn't work....
i opened a new project for this, in the main folder i created assets and a file :
pwd
/home/bboett/AndroidStudioProjects/examen_companion
bboett#hayate:~/AndroidStudioProjects/examen_companion$ ls -l assets/
insgesamt 4
-rw-r--r-- 1 bboett bboett 10 19. Mai 15:14 test.txt
bboett#hayate:~/AndroidStudioProjects/examen_companion$ cat assets/test.txt
Hello!!
then, not trusting android studio, i checked with vi, that in pubspec.yaml everything was ok:
the file ends with:
flutter:
uses-material-design: true
assets:
- assets/
i replaced the spaces, with 2 spaces before uses and assets: and 4 before - assets...
in the _MyHomePageState class i changed :
#override
Widget build(BuildContext context)
{
AssetBundle bundle = DefaultAssetBundle.of(context);
return FutureBuilder<String>(
future: bundle.loadString("assets/test.txt"),
builder: (context, AsyncSnapshot<String> snapshot)
{
if (snapshot.hasData) { return Text(snapshot.data.toString()); }
else { return CircularProgressIndicator(); }
}
);
}
doesn't work.... i never come out of the progress indicator....
so directly in the main i added :
void main() async {
print(await rootBundle.loadString("assets/test.txt"));
runApp(MyApp());
}
and that crashes with :
Launching lib/main.dart on Linux in debug mode...
Building Linux application...
Debug service listening on ws://127.0.0.1:41355/L-ev6_eNIlI=/ws
Syncing files to device Linux...
[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value
#0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:222:39)
#1 AssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:68:33)
#2 CachingAssetBundle.loadString.<anonymous closure> (package:flutter/src/services/asset_bundle.dart:165:56)
#3 _LinkedHashMapMixin.putIfAbsent (dart:collection-patch/compact_hash.dart:311:23)
#4 CachingAssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:165:27)
#5 main (package:examen_companion/main.dart:9:26)
i did after changing anything prior to the run a flutter clean.....
version is :
flutter upgrade
Flutter is already up to date on channel beta
Flutter 2.2.0-10.3.pre • channel beta • https://github.com/flutter/flutter.git
Framework • revision 06e2fd6357 (vor 11 Tagen) • 2021-05-08 11:28:22 -0700
Engine • revision a123e75c60
Tools • Dart 2.13.0 (build 2.13.0-211.14.beta)
flutter doctor run ok too, oh and i have the same error on linux or android, so its not the device....
so i am pretty clueless on how to get this work, since i have the impression to have followed documentation and previous help :(
BTW i thought that flutter was now null, safe... anyway, how do i get this to work?
thanks in advance
[edit]: even stranger.... i replaced
//future: bundle.loadString("assets/test.txt"),
future: bundle.loadString('AssetManifest.json'),
and got :
flutter: {"assets/test.txt":["assets/test.txt"],"packages/cupertino_icons/assets/CupertinoIcons.ttf":["packages/cupertino_icons/assets/CupertinoIcons.ttf"]}
so the file is there??? why can't i open/get it??
[ed2]: ok, i don't get it..... i tryed this directly in main:
print(await rootBundle.loadString('AssetManifest.json'));
and that crashed too with the null exception....
WidgetsFlutterBinding.ensureInitialized() was the key to solve my issue as well as #HannesHultergård wrote. To supplement his answer, the main should be:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
print(await rootBundle.loadString("assets/test.txt"));
runApp(MyApp());
}
I tried your code, and it works for me. Assets can be tricky. Sometimes you will need to restart the app completely after adding a new asset, or uninstall the app completely before running it again. You can also try running flutter clean.
An advice is to add if(snapshot.hasError) print(snapshot.error); before the else in the FutureBuilder just to see what the error is if it still does not work.
The reason you got an error about the null check when printing in main is because you need to add WidgetsFlutterBinding.ensureInitialized(); before using the root bundle to ensure that you have an instance of WidgetsBinding.
You have to put your test.txt inside your assets folder in your project directory.
Also, it would be better if you could add your project directory structure to your post.
Instead of this,
flutter:
uses-material-design: true
assets:
- assets/
Add this,
flutter:
uses-material-design: true
assets:
- assets/test.text
Then run flutter pub get. It should be fine. Let us know if it worked.
Related
When I try to add flutter_svg dependency to add SVG format picture in my project it throws me an error like that:
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_svg-0.19.2+1/lib/src/picture_provider.dart:57:59: Error: No named parameter with the name 'nullOk'.
context != null ? Localizations.localeOf(context, nullOk: true) : null,
^^^^^^
/C:/src/flutter/packages/flutter/lib/src/widgets/localizations.dart:413:17: Context: Found this candidate, but the arguments don't match.
static Locale localeOf(BuildContext context) {
I'm using flutter (Channel master, 1.26.0-18.0.pre.193). and flutter_svg: ^0.19.2+1
I've also with a lower version of this dependency, but still the same error.
add the following dependency
flutter_svg: ^0.20.0-nullsafety.3
instead of
flutter_svg: ^0.19.2+1
Then follow these steps
flutter clean
flutter pub get
flutter run
Looks like flutter_svg didn't migrate to nullsafety, try switch to stable channel and repair cache files.
1. flutter channel stable
2. flutter clean
3. flutter pub cache repair
4. flutter packages get
5. flutter run
If this does not help then try this
https://github.com/dnfield/flutter_svg/issues/479
Yeah, this was an issue for me when I was working on the master branch for a recent project. It was an issue which only came up for the flutter internalisation package.
The main issue is with the intl package:
https://pub.dev/packages/intl/install
To fix this, below the dependencies, please add another section, that will override the intl dependency, which is being pulled by the flutter_localizations package:
dependency_overrides:
intl: ^0.17.0-nullsafety.2
It should now work for the master branch. Another tip, you should avoid working on the master branch, because master changes all the time. You should stick to either stable or beta.
I am using flutter beta version as I am using beta to develop my website, this issue also came to me today, I solved it by running this command,
flutter downgrade
I solved this problem by delete nullOk: true from this line because Localizations.localeOf take context only as a parameter
locale:
context != null ? Localizations.localeOf(context) : null,
instead of
locale:
context != null ? Localizations.localeOf(context, nullOk: true) : null,
or you can change your channel from master channel to stable channel by using this command line on your terminal.
flutter channel stable
flutter clean
I am trying to launch a url in my flutter application. What i'm trying to do is very simple and it works in all other projects except for this one! The browser should be launched on an inkwell onTap event. I tried the exact same code in other projects and worked. I also tried to create a new flutter project and the code worked.
The app does not crash and i don't get any error but on Debug i get a missing plugin exception.
I tried flutter clean and flutter run but didn't work! I tried invalidating cache and restart but also didn't work! I tried removing and re installing the plugin but also didn't work!
Here's the code:
_launchMapsUrl() async {
final url = 'https://www.google.com';
if (await canLaunch(url)) {
await launch(url);
} else {
print('Could not launch $url');
}
}
the onTap:
onTap: () {
_launchMapsUrl();
},
The Compiled and Target SDK versions are 29 and the version of the launcher in my pubspec.yaml is url_launcher: ^5.7.10
For the record the other projects that the code worked in are of the same versions
I think it has something to do with caching issue i'm not really sure, i'm very new to flutter.
Can you please recommend a solution.
I uploaded my application on play store but, when I create IPA for flutter app, then I received these two errors:
Unhandled Exception: MissingPluginException(No implementation found
for method showToast on channel Ponnam Karthik/flutter toast)
Unhandled Exception: MissingPluginException(No implementation found
for method getAll on channel plugins.flutter.io/shared_preferences)
This is my flutter doctor summary:
[✓] **Flutter (Channel stable, v1.12.13+hotfix.8, on Mac OS X 10.15.2 19C57, locale en-IN)**
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 11.3)
[✓] Android Studio (version 3.5)
[✓] Connected device (1 available)
I changed the plugin version. Already used flutter clean and reinstall application, but I can't get it working.
Anyone know how to solve this issue?
Future<List> mainLogin() async {
final response = await
http.post("$api_version/authentication/signin",
body: {"email": email, "password": password});
datauser = json.decode(response.body);
if (datauser.length == 0) {
setState(() {
msg = "Login Fail";
});
} else {
if (datauser['error_description'] == 'Invalid Login Details') {
searchScaffoldKey.currentState.hideCurrentSnackBar();
showLoginError(
context, datauser['error_message'],
datauser['error_description']
);
} else if (datauser['success'] == 1) {
searchScaffoldKey.currentState.hideCurrentSnackBar();
Fluttertoast.showToast(
msg: datauser['success_description'],
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1
);
//===============================================
//Create a session of user
SharedPreferences loginCresentials =
await SharedPreferences.getInstance();
loginCresentials.setString('User_id', datauser['results']['id']);
loginCresentials.setString('User_email', datauser['results'].['email']);
loginCresentials.setString(
'User_fname', datauser['results']['first_name']
);
loginCresentials.setString(
'User_lname', datauser['results']['last_name']
);
loginCresentials.setString(
'User_password', datauser['results']['plain_password']);
loginCresentials.setString('userType', datauser['results'].['userType']);
loginCresentials?.setBool("isLoggedIn", true);
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (BuildContext context) => MyHome(
initialIndex: 0,
)
),
ModalRoute.withName('/')
);
} else {
SharedPreferences loginCresentials =
await SharedPreferences.getInstance();
loginCresentials?.setBool("isLoggedIn", false);
}
}
}
use flutter clean command first, and then re-run the application
I had the same problem while using flutter toast dependency and social media login dependencies like google, Facebook, and Twitter.
I followed these steps and resolved it:
First, u need to test whether these toast and shared preference dependencies are causing problems or some other dependency are the cause.
For testing that, u need to create a new seprate flutter project having the same flutter toast and shared preference dependency and check now if u r able to get toasts or not.
If u r getting toast so there is no problem with ur toast dependency.
The problem might be in ur one of the social media dependency.
In my case, I followed the above steps and found that problem was in facebook dependency. I did not register my app at Facebook developer's console and so reimplemneted that and my app was fine.
If you override the configureFlutterEngine method in your MainActivity class then you will need to register all the plugins by calling GeneratedPluginRegistrant.registerWith(FlutterEngine). See example bellow.
Don't forget to run flutter clean to clear all cache.
Hope this helps you all.
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
#Override
public void configureFlutterEngine(#NonNull FlutterEngine engine) {
// register plugins
GeneratedPluginRegistrant.registerWith(engine);
}
}
I am creating a PopupMenuButton() in the AppBar section.
This is my file:
import 'dart:js';
import 'package:bfdi_app/settings.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
class ProfilePage extends StatefulWidget {
#override
_ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'App_Name',
),
actions: <Widget>[
PopupMenuButton(
icon: Icon(Icons.settings),
onSelected:(value){
if(value==0){
Navigator.push(
context,
MaterialPageRoute(builder: (context)=>SettingPage())
);
}
},
itemBuilder: (context) => [
PopupMenuItem(
child: Text("Settings"),
value:0,
],
),
],
),
}
Now I am facing an error in Console Log:
Compiler message:
lib/Pages/addPost.dart:1:8: Error: Not found: 'dart:js'
import 'dart:js';
^
lib/Profile/profile.dart:1:8: Error: Not found: 'dart:js'
import 'dart:js';
^
I have already added the dependency dart:js, but still getting the same error.
Error:
Go to your flutter installed directory/.pub-cache/hosted/pub.dartlang.org/js-0.6.3-nullsafety.1/lib/js.dart
Delete or comment this line:
export 'dart:js' show allowInterop, allowInteropCaptureThis;
Then try again
I just del import 'package:js'. it works for me.
Sounds like an import issue as soon as you are trying to compile for a native application.
Try searching for and delte the incorrect dart:js import (import 'dart:js';).
Have a look at this GitHub issue #70373
EDIT: I have switched to the master channel and all working fine. Although I don't see any requirement of dart.js in your current code. so you can remove that too
ORIGINAL ANSWER:
I believe you are using stable channel so try to switch to beta channel.
Open your terminal and run,
$ flutter channel beta
Quoting pub.dev:
Depend on it
Add this to your package's pubspec.yaml file:
dependencies:
js: ^0.6.2
Install it
You can install packages from the command line:with pub:
$ pub get
with flutter:
$ flutter pub get
Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.
Import it
Now in your Dart code, you can use:
import 'package:js/js.dart';
in my case just flutter clean solved the issue
Try using the js package: https://pub.dev/packages/js#-installing-tab-
You should try to use package:js instead of dart:js
Actually mine was solved with just a system restart and a "flutter clean" command. (yes I am using beta channel) But weird thing was the files were existed already but the dependencies somehow couldn't read from the dart packages.
You may not running the app on supported platform by library. In my case I was running on Android which library just supported Web as output. No need to clear cache or comment some code.
This solution allowed me to run tests using dart:js & without modifying my local flutter installation.
check if you are not using that package in your project just remove unused packages.
Step -1
Just remove dart:js
Step -2
Run on terminal "flutter clean"
Step -3
Run on terminal "flutter pub get"
Step -4
Run your project
I'm building a react-native app that uses tensorflow to recognize images, I'm following the steps in this tutorial.
I did everything according to the explanations, including the part of "Fetching files". I created the assets folder and put the files in it (the path is correct).
But when I run this code:
const tfImageRecognition = new TfImageRecognition({
model: require('./assets/tensorflow_inception_graph.pb'),
labels: require('./assets/tensorflow_labels.txt'),
});
The app gives the following error:
I already tried to create a new project, I imported the react-native-tensorflow import { TfImageRecognition } from 'react-native-tensorflow';, I updated the cache, I deleted the folder node_modules and also I created the file "rn-cli.config.js" that is requested in the tutorial to give access to the files in the assets folder. Any idea how to fix this?
I'm using expo to run the app on mobile (android).
npm: 5.51
expo: 51.4.0
react-native: 0.54.0
react-native-cli: 2.0.1
This problem didn't occur with me. Try react-native start --reset-cache and then run the app again.
There is a better way to this.
import model from './assets/tensorflow_inception_graph.pb';
import labels from './assets/tensorflow_labels.txt';
const tfImageRecognition = new TfImageRecognition({
model,
labels
});
Restart your server.
I tried the same example as you mentioned I got accessed Image and Text.
I stored files inside assets in the same directory. Can you share code to produce an error that you faced?
async recognizeImage() {
try {
const tfImageRecognition = new TfImageRecognition({
model:require('./assets/tensorflow_inception_graph.pb'),
labels: require('./assets/tensorflow_labels.txt')
})
const results = await tfImageRecognition.recognize({
image: this.image
})
const resultText = `Name: ${results[0].name} - Confidence: ${results[0].confidence}`
this.setState({result: resultText})
await tfImageRecognition.close()
} catch(err) {
alert(err)
}
}
As you mentioned your using expo then I'm assuming that run npm eject already. As react-native-tensorflow this library require native changes
You must add extensions in your rn-cli.config.js, in order to require tensorflow_inception_graph.pb and tensorflow_labels.txt
module.exports = {
getAssetExts() {
return ['pb', 'txt']
}
}
Replace ./ with so ../ , so final code will be -
model: require('../assets/tensorflow_inception_graph.pb'),
labels: require('../assets/tensorflow_labels.txt')