如何设置加载main()时检查连接的布尔值,然后使用它来显示哪个屏幕



我尝试的是我在方法之外使用变量并通过调用方法设置它,但它不起作用。当我检查像_checkConnectivity?SplashScreen(( : WarningScreen((然后它显示错误,例如">未来"没有实例方法"调用"。

import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:algorithm_send_location/pages/home_screen.dart';
import 'package:algorithm_send_location/pages/splash_screen.dart';
import 'package:algorithm_send_location/pages/initial_warning.dart';
import 'package:geolocator/geolocator.dart';
var routes = <String, WidgetBuilder>{
"/home": (BuildContext context) => HomeScreen(),
};
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
bool accessible = false;
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext buildContext) {
_checkConnectivity;
return MaterialApp(
theme: ThemeData(
primaryColor: Colors.amber, accentColor: Colors.green[200]),
debugShowCheckedModeBanner: false,
home: _checkConnectivity ? SplashScreen() : WarningScreen(),
routes: routes);
}
}
get _checkConnectivity async {
var internetResult = await Connectivity().checkConnectivity();
bool locationResult = await Geolocator().isLocationServiceEnabled();
if (internetResult == ConnectivityResult.none || !locationResult) {
//accessible = false;
//print(accessible);
return false;
} else {
//accessible = true;
//print(accessible);
return true;
}
}

如果要使用Future的结果来构建UI,请使用FutureBuilder

例如

void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<bool> _checkConnectivity;
@override
void initState() {
_checkConnectivity = _onCheckConnectivity();
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Material App',
home: _buildHome(),
);
}
Widget _buildHome() {
return FutureBuilder<bool>(
future: _checkConnectivity,
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
final hasConnection = snapshot.data;
return hasConnection ? SplashScreen() : WarningScreen();
default: // Return a loading indicator while checking connection
return Scaffold(
body: Center(
child: SizedBox(
width: 56.0,
height: 56.0,
child: CircularProgressIndicator(),
),
),
);
}
},
);
}
Future<bool> _onCheckConnectivity() {
// Async operation here
}
}

请注意,我们需要使用Future变量作为FutureBuilder中的future参数。根据文档:

未来建设者

未来必须更早获得,例如在 State.initState、State.didUpdateConfig 或 State.didChangeDependencies 期间。在构造 FutureBuilder 时,不得在 State.build 或 StatelessWidget.build 方法调用期间创建它。如果未来与 FutureBuilder 同时创建,则每次重建 FutureBuilder 的父任务时,异步任务都将重新启动。

最新更新