如何使Flutter中的构建函数等待异步函数



Widget构建函数没有等待异步函数更新变量值,这对scaffold webview链接至关重要。我曾尝试将异步函数转移到代码的不同部分,但似乎什么都不起作用。将变量打印到控制台时,首先打印null,然后打印实际值。这里怎么了?

class ProfilePage extends StatefulWidget {
const ProfilePage({Key? key}) : super(key: key);
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
var phone;
var password;
@override
void initState() {
super.initState();
retrieveStringValue();
}
retrieveStringValue() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
password = prefs.getString("password");
phone = prefs.getString("phone");
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: false,
body: SafeArea(
child: WebView(
javascriptMode: JavascriptMode.unrestricted,
initialUrl:
'https://turon.com/app_login.php?phone=$phone&password=$password',
),
),
);
}
}

您可以为此使用FutureBuilder。您也可以稍微简化它,并使用StatelessWidget

在这里,我将更改您的retrieveStringValue函数,以返回具有存储值的MapFutureBuilder将使用这些值来显示数据。

class ProfilePage extends StatelessWidget {
const ProfilePage({Key? key}) : super(key: key);
Future<Map<String, String>?> retrieveStringValue() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final password = prefs.getString("password");
final phone = prefs.getString("phone");
final bool hasData = password != null && phone != null;
if (hasData) {
return {
'password': password,
'phone': phone
}; // this return value is accessed via snapshot.data in FutureBuilder
} else {
return null; // null tells FutureBuilder that no data is stored
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: false,
body: SafeArea(
child: FutureBuilder(
future: retrieveStringValue(), // returns a Map with the stored values
builder: (context, snapshot) {
if (snapshot.hasData) {
final map = snapshot.data! as Map<String, String>;
final password = map['password'];
final phone = map['phone'];
return WebView(
javascriptMode: JavascriptMode.unrestricted,
initialUrl:
'https://turon.com/app_login.php?phone=$phone&password=$password',
);
} else {
return Center(child: CircularProgressIndicator()); // or an indicator that no data is stored
}
},
),
),
);
}
}

相关内容

  • 没有找到相关文章

最新更新