将 Future<bool> 转换为 bool in flutter 以检查数据库是否存在
Convert Future<bool> to bool in flutter to check if database exists or not
我需要将 Future <bool>
转换为 bool
。我知道可以用 then
和 await
来完成,但是怎么做呢?
class MyHomeApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
bool isLogin;
checkDatabase().then((onValue){
isLogin = onValue;
});
if(isLogin) return HomePageScreen();
if(!isLogin) return SignInScreen();
}
Future<bool> checkDatabase() async{
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path + 'koca.db';
return databaseExists(path);
}
}
您可以使用 FutureBuilder
:
class MyHomeApp extends StatelessWidget {
Future<bool> get checkDatabase async {
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path + 'koca.db';
return databaseExists(path);
}
@override
Widget build(BuildContext context) =>
FutureBuilder(
future: checkDatabase,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
if (snapshot.data) {
return HomePageScreen();
} else {
return SignInScreen();
}
}
}
return Center(child: CircularProgressIndicator(),);
},
);
}
我需要将 Future <bool>
转换为 bool
。我知道可以用 then
和 await
来完成,但是怎么做呢?
class MyHomeApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
bool isLogin;
checkDatabase().then((onValue){
isLogin = onValue;
});
if(isLogin) return HomePageScreen();
if(!isLogin) return SignInScreen();
}
Future<bool> checkDatabase() async{
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path + 'koca.db';
return databaseExists(path);
}
}
您可以使用 FutureBuilder
:
class MyHomeApp extends StatelessWidget {
Future<bool> get checkDatabase async {
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path + 'koca.db';
return databaseExists(path);
}
@override
Widget build(BuildContext context) =>
FutureBuilder(
future: checkDatabase,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
if (snapshot.data) {
return HomePageScreen();
} else {
return SignInScreen();
}
}
}
return Center(child: CircularProgressIndicator(),);
},
);
}