0

I used async while using the database, however, the page loads before the data. On the page a lot of widgets are connected to the trophyPoint variable and the page loads before the variable. I used AutomaticKeepAliveClientMixin where the bottom navigation bar is located. It worked for the slide navigations, but when I tapped the navigation bar items, the variable returns null at first and it is the problem.

Edit: I also tried using the SharedPreferences class to load old data but it didn't work either.

Code

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 Answer 1

2

Inside your FutureBuilder you can check:

if(snapshot.hasData){ return body.... } else { return CircularProgressIndicator() } 

The example at the link is pretty good.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.