Flutter:如何让页面等到数据加载?
Posted
技术标签:
【中文标题】Flutter:如何让页面等到数据加载?【英文标题】:Flutter: How to make a page wait until data loads? 【发布时间】:2021-06-02 14:20:45 【问题描述】:我在使用数据库时使用了异步,但是,页面在数据之前加载。在页面上,许多小部件都连接到trophyPoint
变量,并且页面在变量之前加载。我使用了底部导航栏所在的AutomaticKeepAliveClientMixin
。它适用于幻灯片导航,但是当我点击导航栏项目时,变量首先返回 null,这就是问题所在。
编辑:我也尝试使用 SharedPreferences
类来加载旧数据,但它也不起作用。
代码
class MainScreen extends StatefulWidget
static String id = "MainScreen";
@override
_MainScreenState createState() => _MainScreenState();
class _MainScreenState extends State<MainScreen>
int trophyPoint = 0;
final Future<FirebaseApp> _future = Firebase.initializeApp();
//Database instance
final _db = FirebaseDatabase.instance
.reference()
.child("users")
.child(_auth.currentUser.uid);
//method for data
void readData(
_db,
) async
await _db.once().then((DataSnapshot snapshot)
if (!mounted) return;
setState(()
trophyPoint = snapshot.value["tp"];
);
);
/* void tp() async
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
if (!mounted) return;
setState(()
geciciTP = sharedPreferences.getInt("trophy");
sharedPreferences.setInt("geciciTP", geciciTP);
);
*/
@override
void initState()
// TODO: implement initState
super.initState();
@override
void dispose()
// TODO: implement dispose
super.dispose();
@override
Widget build(BuildContext context)
readData(_db);
Size size = MediaQuery.of(context).size;
precacheImage(AssetImage('images/indicator.gif'), context);
return buildContainer(size, context);
Container buildContainer(Size size, BuildContext context)
return Container(
decoration: BoxDecoration(
gradient: kGradientColor,
),
child: Scaffold(
backgroundColor: Colors.transparent,
body: FutureBuilder(
future: _future,
initialData: trophyPoint,
builder: (context, snapshot)
return SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Expanded(
flex: 2,
child: Stack(
fit: StackFit.expand,
children: [
Positioned(
right: size.width / 25,
top: size.height / 60,
child: Container(
width: 100,
height: size.height * 0.055,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(45),
color: kDefaultLightColor,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
FontAwesomeIcons.trophy,
color: Color(0xffFFD700),
),
Text(
" $trophyPoint",
...
gif file of the problem
【问题讨论】:
【参考方案1】:在您的FutureBuilder 中,您可以查看:
if(snapshot.hasData)
return body....
else
return CircularProgressIndicator()
链接上的例子很不错。
【讨论】:
以上是关于Flutter:如何让页面等到数据加载?的主要内容,如果未能解决你的问题,请参考以下文章
Flutter:如何在加载页面之前从 Api 获取数据 [关闭]