Home > Net >  Is there any way to run a function only once in a stateless widget?
Is there any way to run a function only once in a stateless widget?

Time:01-04

Is there any way to run a function only once in a stateless widget?

I want to show an error dialog to user on the home screen if there is no internet connection, and I don't want to show the dialog if the user returns to home screen from any other screen (while the internet is off).

This is the function:

Future<void> _checkInternet(BuildContext context) async {
    try {
      await InternetAddress.lookup('example.com');
    } on SocketException catch (_) {
      showDialog(
        context: context,
        builder: (_) => const CustomErrorDialog(
          contentText:
              'Please turn on your internet connection, otherwise the app will not work properly.',
        ),
      );
    }
  }

CodePudding user response:

Since you want to show a message if there's no connection why not to use flutter offline ? https://pub.dev/packages/flutter_offline .

CodePudding user response:

below modification will display dialog only once and will reset after getting internet connection, you might modify it based on your use case:

 bool didDialogDisplay = false;
    Future<void> _checkInternet(BuildContext context) async {
      try {
        await InternetAddress.lookup('example.com');
        didDialogDisplay = false;
      } on SocketException catch (_) {
        if (!didDialogDisplay) {
          showDialog(
            context: context,
            builder: (_) => const CustomErrorDialog(
              contentText:
                  'Please turn on your internet connection, otherwise the app will not work properly.',
            ),
          );
          didDialogDisplay = true;
        }
    
      }
    }
  • Related