I'm trying to add a firebase analytics track screen to my app.
I tried to enter it in the menu like in the picture below but it always doesn't read
I've tried some code but it doesn't work. For now, the code I'm using is as follows:
FirebaseAnalyticsObserver(analytics: analytics);
onGenerateRoute: widget.appRouter.onGenerateRoute,
builder: EasyLoading.init(),
initialRoute: splashScreenRoute,
navigatorObservers: <NavigatorObserver>[
// FirebaseAnalyticsObserver(analytics: _analytics),
observer
]
and on each screen I add code like this below on each initState()
analytics.setCurrentScreen(screenName: 'Page Detail Mobil');
i have re-run the app but it doesn't work track screen and put in firebase analytic. please help me thank you
I have used different function to track my screens. I have called my logScreens function on routing or you can call it on initState of each pages.
This is my analytic_service.dart
class AnalyticsService {
final FirebaseAnalytics _analytics = FirebaseAnalytics();
Future logScreens({#required String? name}) async {
await _analytics.setCurrentScreen(screenName: name);
}
}
and this is locator.dart
import 'package:get_it/get_it.dart';
import 'analytic_service.dart';
GetIt locator = GetIt.instance;
void setupLocator() {
if (!locator.isRegistered<AnalyticsService>()) {
locator.registerLazySingleton(() => AnalyticsService());
}
}
Call the logScreens function when needed.
locator<AnalyticsService>().logScreens(name: "Dashboard");
And this will be logged in analytics like this.
Try this on DebugView. Click on the screen_view. It will show the screen like this.
Related
i have an app that renders a webpage inside a webview. this actually has a bunch of crypto addresses.
I want them to be automatically made clickable. and when they are clicked - i want to show a popup (some information about the addresses).
can this be done ?
im very unsure if this thing about changing the UI is possible...but in desktop web world, there are extensions that do this. if there are any examples of flutter webview codebases that do this, that would be helpful
the second point - communicating back and forth with the webpage is even more confusing. can this be done at all ? can i receive the data of the click back to main flutter app and then do something ?
Here's a working example
This is achieved as I said by Injecting Js when the webpage loads, as for communication with Flutter, I used the flutter Webview plugin provided JavascriptChannel
The Javascript code looks for a specific element firstly on Page load and secondly while scrolling the webpage (to account for newly created dynamic elements)
Here's how the flow works
JS: assigns the element a new css style (Or in your case make it look like a button) or even create a button and insert it into the webpage
JS: assign on click to the element to call the Flutter JS Channel.
Flutter: Receive message Display a snackbar - you can deeplink or do whatever you want.
As the comments on the JS code say. the scrolling behavior calls every time which is not always ideal, you can use another function make it only trigger on a specific scroll distance
Full working example
import 'dart:developer';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
dynamic ctrl;
// if you have multiple elements, just use querySelector All and loop
const jsCodeToForAnElement = """
// Choose the element
watch();
// I would add dealy to calculate delta between scrolls
// Meaning this code wont watch on every scroll
window.onscroll = watch();
function watch(){
let elm = document.querySelector("main h1");
try{
// Style it
elm.style.cssText = "background: red";
// Add on click
elm.onclick = (event)=> {
var walletHTMLElement = event.target;
// Use native API to communicate with Flutter
jsMessager.postMessage('Wallet clicked: ' + walletHTMLElement.innerHTML);
};
}catch(e){
jsMessager.postMessage('Error: ' + e);
}
}
""";
void main() {
runApp(
MaterialApp(
home: WebViewExample(),
),
);
}
class WebViewExample extends StatefulWidget {
#override
WebViewExampleState createState() => WebViewExampleState();
}
class WebViewExampleState extends State<WebViewExample> {
#override
void initState() {
super.initState();
// Enable virtual display.
if (Platform.isAndroid) WebView.platform = AndroidWebView();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: WebView(
initialUrl: 'https://flutter.dev/',
debuggingEnabled: true,
onWebViewCreated: (WebViewController webViewController) {
ctrl = webViewController;
},
javascriptMode: JavascriptMode.unrestricted,
javascriptChannels: <JavascriptChannel>{
JavascriptChannel(
name: 'jsMessager',
onMessageReceived: (jsMessager) async {
if (jsMessager.message.contains("Wallet")) {
var snackBar = SnackBar(
content: Text(jsMessager.message),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
// Do Other Thing like deeplinking to crypto app
// Deeplink to wallet LaunchApp(wallet) <-- clean wallet string first
}
}),
},
onPageStarted: (String url) async {
ctrl.runJavascript(jsCodeToForAnElement);
},
onPageFinished: (String url) async {},
),
);
}
}
Original Answer
This would be possible by Injecting Javascript into Webviews (This is one idea)
1 - I would wait for the page to load
2 - Modify the HTML content using Javascript
Should be pretty straight forward.
Refer to this Answer to see how it is done in Flutter.
https://stackoverflow.com/a/73240357/6151564
I initiate network request in GetXController, after network call back, I should judge this controller/this page is dealloc or not. If this page is not dealloced, update Page. If this page is dealloced, I do noting. As I know, I can write below codes in flutter origin:
if (mounted) {
// update page
setState({
});
}
So my question is how to write in GetX controller?
There is a property called isClosed in GetxController
so you can use it instead of mounted
class MyController extends GetxController{
...
fun() {
// some code
if(this.isClosed) return;
// code that you want not execute it
}
...
}
mounted can only be called inside Stateful widgets, so you can't use it inside a Controller.
If you are using named routes I think you can get the current name of the page and do something.
if(Get.routing.current == "/home"){
doSomething();
}
the mounted bool is specific only for the StateFulWidget, I could think of passing it as a Stream<bool>to the controller, then use it, But, this is not the ideal solution and it can be very problematic.
On the other hand, you can check on mounted before calling the method, like this:
// ....
onPressed: () {
if (mounted) {
controller.sendRequest();
}
},
// ....
According to the Flutter's official deep linking page, we do not require any plugin or native Android/iOS code for handling deep links.
But it doesn't really tell us how we can get the data from that link. I'm talking from coding perspective. Sure, they have written in there that:
But this does not tell me where should I write what code to actually get the complete link. I've looked for examples/tutorials but I'm unable to find anything that is not using a plugin for handling deep linking.
Right now, all I've done is add <intent-filter> tags in AndroidManifest.xml file and on clicking the link, my app has started to show up. But I don't know how to extract data from that link.
Is there anyone who can guide me here? Thanks in advance.
You need platform specific code to handle deep linking. If you follow link mention in documention, you will find complete example.
private val CHANNEL = "poc.deeplink.flutter.dev/channel"
private var startString: String? = null
override fun configureFlutterEngine(#NonNull flutterEngine:FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine)
MethodChannel(flutterEngine.dartExecutor, CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "initialLink") {
if (startString != null) {
result.success(startString)
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val intent = getIntent()
startString = intent.data?.toString()
}
Flutter Code:
class DeepLinkBloc extends Bloc {
//Event Channel creation
static const stream = const
EventChannel('poc.deeplink.flutter.dev/events');
//Method channel creation
static const platform = const
MethodChannel('poc.deeplink.flutter.dev/channel');
StreamController<String> _stateController = StreamController();
Stream<String> get state => _stateController.stream;
Sink<String> get stateSink => _stateController.sink;
//Adding the listener into contructor
DeepLinkBloc() {
//Checking application start by deep link
startUri().then(_onRedirected);
//Checking broadcast stream, if deep link was clicked in opened appication
stream.receiveBroadcastStream().listen((d) => _onRedirected(d));
}
_onRedirected(String uri) {
// Here can be any uri analysis, checking tokens etc, if it’s necessary
// Throw deep link URI into the BloC's stream
stateSink.add(uri);
}
#override
void dispose() {
_stateController.close();
}
Future<String> startUri() async {
try {
return platform.invokeMethod('initialLink');
} on PlatformException catch (e) {
return "Failed to Invoke: '${e.message}'.";
}
}
}
Follow this link for more detail.
https://medium.com/flutter-community/deep-links-and-flutter-applications-how-to-handle-them-properly-8c9865af9283
The Flutter way to do that, assuming you've already made the steps in the guide you posted, is to create a onGenerateRoute and/or onGenerateInitialRoutes handlers in your MaterialApp so that these handlers deals with the routes passed or pushed by the framework according to the described behaviors. You can even create an expected named route coming from a deeplink on the routes property of MaterialApp, even though I believe the dynamic generation of routes is more appropriate due to the dynamic nature of deeplinking, specially if you're dealing with "authentication needed content" inside your app.
Or, if you don't want to pass trough the platform specific code, you could use firebase dynamic links. That would allow to easily listen to links coming from both platforms and you also get the advantage that your link would bring up the store listing page if the user doesn't have the app installed.
I've written a full example here: https://gbaccetta.medium.com/flutter-deep-linking-with-firebase-dynamic-links-and-bloc-architecture-660f0517fbc2
Do for android as said in the web page: "Add a metadata tag and intent filter to AndroidManifest.xml inside the tag with the ".MainActivity" name". Do what required for ios too.
Then use onGenerateRoute in the usual way in MaterialApp, don't use "routes:". For example:
onGenerateRoute: (settings) {
print("settings.name " + settings.name.toString());
if (settings.name == '/') return MaterialPageRoute(builder: (_) => ScreenStart());
return MaterialPageRoute(builder: (_) => ScreenUnknown());
},
Then to simulate I did:
cd /Users/Utente/AppData/Local/Android/Sdk/platform-tools
adb shell
am start -W -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "http://theaddressichoosed.com/helloworld?byebye"
And
print("settings.name " + settings.name.toString());
printed
settings.name /helloworld?byebye
After spending some time on this, here's my take using the Navigator 2 API. It also shows how to perform query and path arguments parsing. Hope it will save someone the time I spent researching this.
Obviously you also need to edit your platform-specific build files (such as AndroidManifest.xml for Android) as shown in the Flutter Deep Linking page.
A special note for Android 12 and above: you'll also need to securely approve the app's domain in the Google Play Developer Console for deep linking to work.
class App extends StatelessWidget {
const App({super.key});
#override
Widget build(BuildContext context) => MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => HomeScaffold(),
'/route1': (context) => const RouteOneScaffold(),
'/route2': (context) => const RouteTwoScaffold(),
// Other routes which don't need any sort of query parsing
},
onGenerateRoute: (settings) {
// This is executed to determine which route to follow if no adequate entry is found in the `routes` array above.
// Here we can parse path and query parameters as we like.
final fullRoute = settings.name;
if (fullRoute == null) {
return null;
}
final routeData = Uri.tryParse(fullRoute);
if (routeData == null) {
return null;
}
final pathParameters = routeData.pathSegments;
final queryParameters = routeData.queryParameters;
// Here you can write your route handling logic
return MaterialPageRoute(builder: (context) => RouteThreeScaffold(pathParameters,queryParameters));
},
);
}
I'm making a LoginScreen, in LoginScreen i check data in database for know user logged or not for each times open app.
If user logged, the app will switched to HomeScreen.
I have a problem, i had logged in LoginScreen and then the app switched to HomeScreen. But my app's not standing in HomeScreen, it's continuing push new HomeScreen and looping this push action.
My code:
goToHomeIfAvailable() async {
// Go to HomeScreen if available
if (await this._databaseProvider.tokenTableIsEmpty() == false) {
print('Logged');
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomeScreen()),
);
}
}
#override
Widget build(BuildContext context) {
// In first times user open app=> create DB and go to HomeScreen if available
_databaseProvider.openOrCreate().then((_) async {
await goToHomeIfAvailable();
});
/* Return a widget bellow */
}
DatabaseProvider.dart:
class DatabaseProvider {
String _path = 'O2_DB.db';
Database _database;
Map _tableName = {'token': 'token_tbl'};
Future openOrCreate() async {
this._database = await openDatabase(this._path, version: 1,
onCreate: (Database db, version) async {
await db.execute('CREATE TABLE IF NOT EXISTS ' +
this._tableName['token'] +
' (token_id integer primary key autoincrement, token text)');
});
}
}
Build is called many times during the app life cycle - & its better to always put our logic outside build method. Its normal Behavior.
In your case - As build was called each time the method - goToHomeIfAvailable() was called hence multiple push.
Moving goToHomeIfAvailable() out of build to initState() will solve the issue.
I am creating a list of businesses through RestAPI in initstate. I need to use sharedpreference value as one of its parameter but when i try to load data, the sharepreference value is null initial but that value can be used in other widgets easily.
The problem is how to read sharepreference value and use at the same time in initstate.?
I have tried many options like taking my api out of initstate and defining with async function and call it in initstate.
**#override
void initState() {
super.initState();
loadData();
getBizList();
}
getBizList() async {
await api
.bizListAPI(widget.subCatid, savedCityID, supSubFinal, areaFinal)
.then((response) {
setState(() {
bizListOBJ = response;
});
});
}
loadData() async {
SharedPreferences savedPref = await SharedPreferences.getInstance();
setState(() {
savedCity = (savedPref.getString('savedCity') ?? "Mumbai");
savedCityID = (savedPref.getString('savedCityID') ?? "1");
});
}**
in above code i am able to get or read data and show city name from sharedpreference(savedCity) which is in appbar but i want to use savedcityID data to pass in my api in initstate.
I also tried to use following plugin
[https://medium.com/#greg.perry/a-flutter-class-for-app-preferences-a256166ecc63.][1]
With this I was able to do what i wanted but each time i close my app and open again ...
i got following error
"_prefsInstance != null,
"Maybe call Prefs.getKeysF() instead. SharedPreferences not ready yet!");"
after that when i go back and open page again, the app and biz list works perfect till again i close my app.
[1]: https://medium.com/#greg.perry/a-flutter-class-for-app-preferences-a256166ecc63
sorry for my any noob explanation or question. Actually this is my 1st question in stack and I am beginner in flutter.
Can you try this?
void initState() {
super.initState();
loadData().then((_) {
getBizList();
});
}
You need to use set state inside init state because
loadData();
getBizList();
are async function so you need to refresh page to get value.
Try this
#override
void initState() {
// TODO: implement initState
super.initState();
setState(() {
loadData();
getBizList();
});
}