在Web视图中获取值的速度不够快



嘿,我遇到的问题有点奇怪。。因此,我使用的是webview,作为初始URL,我使用从Google cloud_firestore获得的值。。现在,从我的fireStore数据库中检索这个链接大约需要2秒钟,在这段时间里,我的代码正在运行,并且认为"thankGod"变量是空的。。因此,即使是Text小部件也会说"thankGod"变量在前2秒为null,然后在..之后返回值。。但这并不好,因为我的webView在为空时使用了"thankGod"变量。。这是我的密码。

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:webview_flutter/webview_flutter.dart';

class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
final Completer<WebViewController> _completer = Completer<WebViewController>();
DocumentReference documentReference = Firestore.instance.collection('dailyPictures').document('t1');
Future<void> getData() async{
await documentReference.get().then((datasnapshots) {
setState(() {
thankGod = datasnapshots.data['picture1'];
});
});
}

String thankGod;

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

}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(1800),
),
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
margin: EdgeInsets.fromLTRB(
20,
20,
20,
20
),
child: 
Text(
thankGod,
style: TextStyle(
color: Colors.white,
fontSize:32
),
)
WebView(
initialUrl: thankGod,
debuggingEnabled: true,
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: ((WebViewController webViewController){
_completer.complete(webViewController);
}),
),

));
}
}

求你了,我需要帮助。。帮助我分享这个问题

为getData函数设置返回类型String;

Future<String> getData() async {
DocumentSnapshot = await documentReference.get();
return datasnapshots.data['picture1'];
}

使用FutureBuilder获取您的数据并构建您的WebView;

FutureBuilder<String>(
future: getData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
String initialUrl = snapshot.data;
return WebView(
initialUrl: initialUrl,
debuggingEnabled: true,
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: ((WebViewController webViewController) {
_completer.complete(webViewController);
}),
);
}
return CircularProgressIndicator();
},
)

注意:您不需要在initState内部调用getData()

最新更新