0

I want my flutter app run only if internet connection is available. If the internet is not present show a dialog(internet is not present) I'm using conectivity plugin but still not satisfied.

Here is my main function

Future main() async {
  try {
  final result = await InternetAddress.lookup('google.com');
  if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
    print('connected');
  }
} on SocketException catch (_) {
  print('not connected');
}
  runApp(MyApp());}
1
  • check internet whether online or offline if offline show alert i seen so many application. Commented Apr 7, 2019 at 5:32

1 Answer 1

2

You can't use dialog in main() method directly because there is no valid context available yet.

Here is the basic code of what you are looking for.

void main() => runApp(MaterialApp(home: MyApp()));

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    Timer.run(() {
      try {
        InternetAddress.lookup('google.com').then((result) {
          if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
            print('connected');
          } else {
            _showDialog(); // show dialog
          }
        }).catchError((error) {
          _showDialog(); // show dialog
        });
      } on SocketException catch (_) {
        _showDialog();
        print('not connected'); // show dialog
      }
    });
  }

  void _showDialog() {
    // dialog implementation
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
            title: Text("Internet needed!"),
            content: Text("You may want to exit the app here"),
            actions: <Widget>[FlatButton(child: Text("EXIT"), onPressed: () {})],
          ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Internet")),
      body: Center(
        child: Text("Working ..."),
      ),
    );
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Undefined name 'context'.
The getter 'isNotEmpty' isn't defined for the class 'Future<List<InternetAddress>>'.dart(undefined_getter)
Nope @CopsOnRoad
@richie Ok, the reason was your original code didn't include catchError() I have added it now and it is 100% working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.