Search code examples
flutternavigationflutter-getx

Navigations count in flutter


I need to show a pop up after user change 3 page in app.

How can I count number of navigations in flutter ?

I used getx for change pages in app and had observer analytics of firebase.


Solution

  • you can track the changed page using a variable. There is no such thing as global variable in dart programing language. So this is a way around implementing a global variable in dart.

    Steps: Create a file called global.dart and declare a variable

    eg: int pageCount = 0;

    now import this file as import 'package:..../global.dart';

    and increment the pageCount variable wherever there is a Navogator.push or page change is triggered.

    Imp Note: If you use this way then on every app restart the pageCount variable resets (initialised) to 0 and the pop will be shown again to the user after pageCount=3


    Now if this can be avoided if you use a sharedPreferences plugin. Store the pageCount as a shared preferences. The update of the variable should be done in the same way as explained above.

    Then on every app start read this variable if the variable == 3 then you can skip the showing of the popup.

    plugin link: https://pub.dev/packages/shared_preferences

    This post explains very well how to implement shared preferences in your flutter app: https://medium.com/flutterdevs/using-sharedpreferences-in-flutter-251755f07127


    This is the most tedious way:

    Now if you are not comfortable in using shared preferences then, you can store the variable in a text file or a JSON file using path_provider plugin with the dart:io library.

    everything explained here on reading and writing files : https://flutter.dev/docs/cookbook/persistence/reading-writing-files

    if you choose to use JSON file to save the variable then you can do as follows:

    • open a file called config.json or any_name.json
    • use file.writeAsStringSync('{"pageCount":3}'), whatever the page change count is at that instance.
    • Read this file on every app start, check if the page count is 3, then implement your logic and so on.