简体   繁体   English

颤振:在没有互联网连接时返回一个页面

[英]flutter: return a page when no internet connection

i created flutter app that shows a taost message when no internet connection, but i was trying to return a page clarifies that no internet connection ( before entering the app) instead of toast message is there a way to do it?我创建了 flutter 应用程序,在没有互联网连接时显示 taost 消息,但我试图返回一个页面,说明没有互联网连接(在进入应用程序之前)而不是 toast 消息,有没有办法做到这一点?

 class _NotificationState extends State<Notification> { var subscription; var connectionStatus; @override void initState() { subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) { setState(() => connectionStatus = result); checkInternetConnectivity(); }); checkInternetConnectivity(); // checkLoginStatus(); super.initState(); } checkInternetConnectivity() { if (connectionStatus == ConnectivityResult.none) { return Fluttertoast.showToast( msg: "Check your internet connection", toastLength: Toast.LENGTH_LONG, gravity: ToastGravity.TOP, timeInSecForIosWeb: 10, backgroundColor: Colors.red, textColor: Colors.white, fontSize: 16.0 ); } } //PS: i tried to return Internet() page instead but it's not working @override dispose() { super.dispose(); subscription.cancel(); } Widget build(BuildContext context) {

Your initState method contains duplicate method calls to checkInternetConnectivity .您的initState方法包含对checkInternetConnectivity重复方法调用。 Remove one of them:删除其中之一:

@override
  void initState() {
subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {         
        setState(() => connectionStatus = result);
        checkInternetConnectivity();
});
    
    // checkInternetConnectivity(); <--- Remove this
    // checkLoginStatus();
    
    super.initState();
  }

Finally, your method should look something like this:最后,您的方法应如下所示:

void checkInternetConnectivity() {
   if (connectionStatus == ConnectivityResult.none) {
     Navigator.of(context).push(MaterialPageRoute(
       buider: (BuildContext context) => Internet(),
     )); 
   }
}

Two common ways of navigating from one page to another从一页导航到另一页的两种常见方式

  1. Without the use of route不使用路由
  Navigator.push(
        context,
        MaterialPageRoute(
        builder: (context) => InternetPage(
            // you can pass parameter here to the next page
            // remember to create instance of dataToNextPage at the page you are navigating to
            dataToNextPage: dataFromCurrentPage,
        ),
 ));
  1. With the use of named Route.使用命名路由。 You need to specify the route you will be using link for more info您需要指定您将使用的路线链接以获取更多信息
Navigator.pushNamed(context, '/internetPage', arguments: {});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM