Anyone know how to ping google and get latency in Flutter? I am using dart_ping but fail to ping.
Try dart_ping:
Setup:
dependencies:
dart_ping: ^1.0.0
Notes:
Watch the spacing. It should be excatly correct in the pubspec.yaml . You can add the second line (dart_ping: ^1.0.0) right below cupertino_icons: ^....
Remember to click on Packages Get (in Android Studio).
Usage:
import 'package:dart_ping/dart_ping.dart';
main() async {
var stream = await ping("google.com", times: 5);
print("Pinging google.com");
stream.listen((d) {
print(d.time.inMilliseconds);
});
}
Related
I am trying to implement FCM for a flutter web project.
When I run the project in the localhost, it works fine. But when I upload it to firebase hosting (After running flutter build web), I am getting errors.
On the main.dart file, I am trying to get the device token:
final fcmToken = await FirebaseMessaging.instance.getToken(
vapidKey:
"my_key");
However, I am getting this error in the console:
main.dart.js:4430 Uncaught MissingPluginException(No implementation found for method Messaging#getToken on channel plugins.flutter.io/firebase_messaging)
I added the firebase messaging package in my pubspec.yaml file:
firebase_messaging: ^14.2.1
Additionally, I added the service worker code as explained here: https://firebase.flutter.dev/docs/messaging/usage/
Here is my index.html script code:
<script>
window.addEventListener("load", function (ev) {
// Download main.dart.js
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/firebase-messaging-sw.js");
}
_flutter.loader
.loadEntrypoint({
serviceWorker: {
serviceWorkerVersion: serviceWorkerVersion,
},
})
.then(function (engineInitializer) {
return engineInitializer.initializeEngine();
})
.then(function (appRunner) {
return appRunner.runApp();
});
});
</script>
It looks like a problem with the firebase_messaging package, but I'm using the latest one. Also what I can't understand is why it's working in localhost but not production.
Thoughts anyone?
Running flutter clean solved the problem
Is it possible to host a Flutter web app on a local environment using a Flutter desktop-based app?
The google-search for a solution like this can be difficult, since it involves many keywords that lead to similar situations (online hosting when you need a local solution, command-line only solution, and so on).
After some digging, I ended up using the shelf package to deploy my own Flutter web app on a local network. I developed this for Windows only, so I can't guarantee it will work on other platforms.
First thing to do is obviously adding the shelf package in your pubspec.yaml: after that, this is how my main method looks like
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf_router/shelf_router.dart' as shelf_router;
[...]
void main() async{
[...]
var secureContext = SecurityContext();
try {
//privKey and cert are the String names of the two files for the SSL connection,
//placed in the root directory of the flutter project or along with the .exe file (when released)
secureContext.usePrivateKey(privKey);
secureContext.useCertificateChain(cert);
} catch (error) {
logger.e("Error on init SecurityContext");
}
try {
//this is the handler that deploys the files contained in 'webAppFolder': I just simply pasted the result of
//the flutter webapp building inside (the index.html file is the default one for flutter web)
//and put the folder in the root of the flutter project (or, again, in the same folder with the .exe file when released)
final _staticHandler = createStaticHandler("webAppFolder", defaultDocument: 'index.html');
//this I kept just for a reminder on how to deploy a static page, if needed
final _router = shelf_router.Router()
..get(
'/time',
(request) => shelf.Response.ok(DateTime.now().toUtc().toIso8601String()),
);
final cascade = shelf.Cascade()
.add(_staticHandler)
.add(_router);
try {
var server = await shelf_io.serve(
cascade.handler,
InternetAddress.anyIPv4,
mainPort, //this is the number of the port on which the webapp is deployed (I load this from a .ini file beforehand
securityContext: secureContext,
);
// Enable content compression
server.autoCompress = true;
logger.i("Serving at https://${server.address.host}:${server.port}");
} catch (err) {
logger.e("Error while serving");
logger.e(err.toString());
}
} catch (err) {
logger.e("Error while creating handler");
logger.e(err.toString());
}
runApp(MaterialApp(
[...]
This is the part related to the deploy of a web app: since the flutter desktop app already provides a GUI, I used that to add some maintenance and testing utilities to check if everything is working fine.
For more details regarding shelf, refer to their API on their pub.dev page.
My app was working normally since today.I already included Firebase Storage in my Android Flutter App and it works after that today I get AppCheck Errors suddenly. I was not include App Check for our project or not enforced in settings. After that I was following the official documentation for initialization appcheck : https://firebase.flutter.dev/docs/app-check/usage.
This is my Kotlin MainActivity:
import android.os.Bundle
import com.google.firebase.FirebaseApp
import com.google.firebase.appcheck.FirebaseAppCheck
import com.google.firebase.appcheck.debug.DebugAppCheckProviderFactory
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
FirebaseApp.initializeApp(/*context=*/ this);
val firebaseAppCheck = FirebaseAppCheck.getInstance()
firebaseAppCheck.installAppCheckProviderFactory(
DebugAppCheckProviderFactory.getInstance())
super.onCreate(savedInstanceState)
}
}
and this is my main():
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await FirebaseAppCheck.instance.activate();
runApp(MyApp());
}
I also added this to my app/build.gradle
dependencies {
implementation 'com.google.firebase:firebase-appcheck-debug:16.0.0-beta01'
}
When I make a request to firebase storage, I would expect something like this in my console:
D DebugAppCheckProvider: Enter this debug secret into the allow list in the Firebase Console for your project: 123a4567-b89c-12d3-e456-789012345678
Instead, I'm getting an error:
2021-11-21 18:11:51.442 2091-3452/com.sekspir.grind4gain W/ExponenentialBackoff: network unavailable, sleeping.
2021-11-21 18:11:53.500 2091-3452/com.sekspir.grind4gain W/StorageUtil: Error getting App Check token; using placeholder token instead. Error: com.google.firebase.FirebaseException: Error returned from API. code: 403 body: App attestation failed.
2021-11-21 18:12:11.136 2091-3633/com.sekspir.grind4gain V/NativeCrypto: SSL handshake aborted: ssl=0xdaa42da8: I/O error during system call, Connection reset by peer
Did I miss something here? I am using a real Android device with flutter debug build.
This is Firestore AppCheck Stats looks both of request income
But in Storage session there are not any request fail or success.
Can you double check that you correctly enabled the enforcement ?
It is required to work with Firebase Storage solutions.
Are you using your app in "PWA" mode or in "Native" mode ?
The Recaptcha may be mandatory depending on how your app is distributed.
await FirebaseAppCheck.instance.activate(
webRecaptchaSiteKey: 'recaptcha-v3-site-key',
);
I'm not sure about your implementation of the appcheck-debug dependency on the Android Native side.
Since it's already implemented by the Flutter library itself, you should remove it.
Personal note : I had troubles with FirebaseAppCheck on some devices, while it was working perfectly on other devices.
This library is still in beta and I would recommend to wait before using it in production.
The following code errors are not showing on firebase console for some reason:
FirebaseCrashlytics.instance.log('This is brilliant log!');
FirebaseCrashlytics.instance.setCustomKey('str_key', 'hello buffallo');
try {
throw 'error_example';
} catch (e, s) {
FirebaseCrashlytics.instance.recordError(e, s);
}
await FirebaseCrashlytics.instance.recordError(
'No error',
StackTrace.empty,
reason: 'a non-fatal error',
);
However, when I force a crash i.e. use
FirebaseCrashlytics.instance.crash()
This shows up fine! Is there something I am doing wrong?
I am using this version in pub spec: firebase_crashlytics: ^0.4.0+1
I can't use the latest version because of some external dependencies (before you ask)
The errors recorded by recordError are listed as non-fatal exceptions in the Firebase console. At least for iOS they are only uploaded when the app was killed and reopened.
I'm trying to seed the Firebase Storage Emulator. I've added a json file to my project and I'm trying to upload this file to the Storage Emulator during the seed phase:
await firebaseAdmin
.storage()
.bucket()
.upload(path.join('./data/cars.json'), {
destination: `vehicles/cars.json`,
});
Unfortunately this does not seem to work and I'm running into the following error:
TypeError: Cannot read property 'length' of undefined
The way I did this was by using firebase-tools
firebaseCli.emulators.start({
project: "project-id",
import: "path-to-file.json"
})
This will work only if the firebase emulator setup is done correctly and the data you are trying to import has the correct format.
For the Firebase Storage Emulator to work you need to initialize it in the Admin SDK:
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert('path/to/credential'),
storageBucket: "bucket-name",
});