Я работаю с сеткой, в которой для каждой ячейки задано число aws. Эти числа хранятся в SharedPreferences, что является лучшим способом получить этот список чисел из SharedPreferences до того, как сетка будет нарисована в пользовательском интерфейсе. Я попытался вызвать метод для метода build , но не сработал.
@override
void initState() {
grid = blankGrid();
gridNew = blankGrid();
super.initState();
}
@override
Widget build(BuildContext context) {
...
WidgetsBinding.instance.addPostFrameCallback((_){
initializeGame();
});
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
'2048',
style: TextStyle(fontSize: 25.0, fontWeight: FontWeight.bold),
),
backgroundColor: Color(MyColor.gridBackground),
),
body: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
Container(
height: height,
child: Stack(
children: <Widget>[
Padding(
padding: EdgeInsets.all(10.0),
child: GestureDetector(
child: GridView.count(
primary: false,
crossAxisSpacing: 10.0,
mainAxisSpacing: 10.0,
crossAxisCount: 4,
children: getGrid(gridWidth, gridHeight),
),
),
...
],
),
color: Color(MyColor.gridBackground),
),
Padding(
padding: EdgeInsets.all(10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: Color(MyColor.gridBackground),
),
child: Padding(
padding: EdgeInsets.all(10.0),
child: IconButton(
iconSize: 35.0,
icon: Icon(
Icons.refresh,
color: Colors.white70,
),
onPressed: () {
setState(() {
grid = blankGrid();
gridNew = blankGrid();
grid = addNumber(grid, gridNew);
grid = addNumber(grid, gridNew);
score = 0;
isgameOver=false;
isgameWon=false;
});
},
),
),
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: Color(MyColor.gridBackground),
),
child: Padding(
padding: EdgeInsets.all(10.0),
child: Column(
children: <Widget>[
Text(
'High Score',
style: TextStyle(
color: Colors.white70,
fontWeight: FontWeight.bold),
),
FutureBuilder<String>(
future: getHighScore(),
builder: (ctx, snapshot) {
if (snapshot.hasData) {
return Text(
snapshot.data,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold),
);
} else {
return Text(
'0',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold),
);
}
},
)
],
),
),
)
],
),
)
],
),
),
),
);
}
Метод, который получает данные из общих настроек:
void initializeGame() async{
sharedPreferences = await SharedPreferences.getInstance();
contains = sharedPreferences.getKeys().toList().contains("game_state");
if(isFirstTime && contains){
getGameState();
} else {
...
}