I am having big time trouble with getting the data from my method getAllPlayerData()
outside the .then((Value)
.
The "bad print" in my code shows up before my "good print". I want to be able to use my variable "TheStats" in my code with all the data inside of it and not a "null" value or "instance of Future<Dynamic"
import 'package:cleanmaybe/Controllers/players_controller.dart';
import 'package:flutter/material.dart';
class PlayerStatView extends StatefulWidget {
const PlayerStatView({Key? key}) : super(key: key);
@override
State<PlayerStatView> createState() => _PlayerStatViewState();
}
class _PlayerStatViewState extends State<PlayerStatView> {
var theStats;
@override
void initState() {
getAllPlayerData().then((value) {
theStats = value;
print("Good print $theStats");
});
super.initState();
}
@override
Widget build(BuildContext context) {
print("bad print $theStats");
return Container();
}
}
This is my "getAllPlayerData()"
getAllPlayerData() async{
SharedPreferences sp = await _pref;
int? id = sp.getInt('idPlayer');
final statAccess = DatabaseModel();
var lookForData = await statAccess.getPlayerData(id);
return lookForData;
}
And if you need it, this is my getPlayerData(id)
method that fetches all the data from my database:
Future getPlayerData(idPlayer) async {
var dbCoach = await db;
var dataPlayer = dbCoach!.rawQuery("SELECT * FROM players WHERE"
" idPlayer = '$idPlayer'");
return dataPlayer;
}
CodePudding user response:
Your "bad print" will practically always run before "Good print" as long as getAllPlayerData()
take any time at all to process with this construct.
There are several ways to handle this, but a suggestion is to use the FutureBuilder
widget for it (as @pskink just wrote as a comment :)) Check the offical documentation.