我有一个像这样的 flutter 应用程序
main.dart
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 文件调用网络检查功能,所以
网络.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
}
}
}
所以我的问题是,如果 checkNetwork()
函数失败或响应为“否定”,那么我想重定向/显示 main.dart 或另一个页面中的另一个页面。
最佳答案
(注意:将以下代码包装在零时间延迟的 future 中只是为了确保当我们使用它时上下文已准备好)
@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()));
});
});
}
关于android - 当条件成立时,Flutter 重定向到新屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61413901/