Flutter从班级重定向新屏幕

我有一个扑扑的应用程序,例如

主镖

import 'package:flutter/material.dart';
import 'network.dart';

void main() => runApp(HomePage());

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}


class _MyAppState extends State<HomePage> {
  String _message = '';
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  _register() {
    _firebaseMessaging.getToken().then((token) => print(token));
  }

  @override
  void initState() {
    super.initState();
    getMessage();

    TestNetwork.checkNetwork().then((val){
          print(val);
    });
  }

  void getMessage(){
    _firebaseMessaging.configure(
        onMessage: (Map<String, dynamic> message) async {
      print('on message $message');
      setState(() => _message = message["notification"]["title"]);
    }, onResume: (Map<String, dynamic> message) async {
      print('on resume $message');
      setState(() => _message = message["notification"]["title"]);
    }, onLaunch: (Map<String, dynamic> message) async {
      print('on launch $message');
      setState(() => _message = message["notification"]["title"]);
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new MaterialApp(

        home: new Scaffold(
          body: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text("Message: $_message"),
            OutlineButton(
              child: Text("Register My Devices"),
              onPressed: () {
                _register();
              },
            )

          ]),
        ),
      );

  }
}

我正在从另一个Dart文件调用网络检查功能,所以

网络镖

import 'package:http/http.dart' as http;
import 'dart:async';

class TestNetwork {

static String mainWebServiceURL="http://mydmain.com/webservicepath/";

static Future<bool> checkNetwork() async {
  try{
      Map<String,String> _user = {};
      _user['name'] = "Username";
      final response= await http.post(mainWebServiceURL+'/index.php',
        body: _user,
      );
      if(response.statusCode==200)
        return Future.value(true);
        else
        // I want to redierct to another page in main.dart page
  }
  catch (_) {
    // I want to redierct to another page in main.dart page
  }

}

}

So my question is if checkNetwork() function fails or the response is "negative" then I want to redirect / show another page in main.dart or another.

评论
  • qquasi
    qquasi 回复

    (注意:在零时延的将来包装下面的代码只是为了确保上下文在我们使用时准备就绪)

     @override
      void initState() {
        super.initState();
        getMessage();
    
       Future.delayed(Duration.zero,(){
         TestNetwork.checkNetwork().then((val){
           Navigator.of(context).push(MaterialPageRoute(builder: (ctx)=>MySuccessRoute()));
         },onError: (){
           Navigator.of(context).push(MaterialPageRoute(builder: (ctx)=>MyFailureRoute()));
         });
       });
      }
    
  • tqui
    tqui 回复

    我对此有一个想法,您可以执行以下其中一项操作:

    1. Let your checkNetwork function return true or false, and then use this boolean value to determine which widget to use in the home field of the MaterialApp widget.
    2. Create a new widget, maybe SplashScreen which will always be the one used in the home field of MaterialApp, and in this widget you checkNetwork and do the proper Navigator.push() according to the boolean result.

    我个人更喜欢方法2,因为它可以给您更多的控制权。