import "package:shared_preferences/shared_preferences.dart";
import "package:flutter/material.dart";
import "dart:async";
import "dart:io";
void main() => runApp(MyApp());
getIntSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
int numbP = prefs.getInt('numbPage') ?? 0;
return numbP;
}
int numbPage = getIntSF();
class MyApp extends StatelessWidget {
final contr = ScrollController();
final Bloc bloc = Bloc();
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Бла Бла',
theme: ThemeData(primarySwatch: Colors.green),
home: Scaffold(
appBar: AppBar(
title: StreamBuilder(
initialData: numbPage,
stream: bloc.press,
builder: (context, snapshot) => Text(
'Бла Бла ${snapshot.data.toString()}',
style: TextStyle(fontSize: 18.0)),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.exit_to_app),
tooltip: 'Выйти из приложения',
onPressed: () {
addIntToSF();
exit(0);
})
]),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
StreamBuilder(
initialData: book[numbPage],
stream: bloc.txt,
builder: (context, snapshot) {
return Expanded(
child: SingleChildScrollView(
controller: contr,
child: Text('${snapshot.data}',
style: TextStyle(
fontSize: 20.0,
fontStyle: FontStyle.italic))));
})
])),
bottomNavigationBar: BottomAppBar(
shape: CircularNotchedRectangle(),
child: Container(height: 50.0)),
floatingActionButton: Container(
width: 50.0,
height: 50.0,
child: FloatingActionButton(
onPressed: () {
bloc.butPres.add(numbPage);
contr.jumpTo(0.0);
},
tooltip: 'Бла Бла',
child: Icon(Icons.add))),
floatingActionButtonLocation: FloatingActionButtonLocation.endDocked),
);
}
addIntToSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt('numbPage', numbPage);
}
}
class Bloc {
Bloc() {
_contrIn.stream.listen((data) {
numbPage++;
_contrOut.add(numbPage);
_contrOutTxt.add(book[numbPage]);
});
}
get butPres => _contrIn;
var _contrIn = StreamController<int>();
var _contrOut = StreamController<int>();
get press => _contrOut.stream;
var _contrOutTxt = StreamController();
get txt => _contrOutTxt.stream;
void dispose() {
_contrIn.close();
_contrOut.close();
_contrOutTxt.close();
}
}
List book = [
"мама",
"папа",
"бабушка",
"дедушка",
"сын",
"дочь",
];
Ожидалось, что код будет читать из шаред преференсес значение переменной, а после выхода из приложения сохранять его туда же. При следующем старте на экране должна отображаться бывшей последней в предыдущей сессии строка, например "мама".
async
. У вас данные не успевают доставаться, а вы их уже используете (точнее ихnull
). 2) Вы пытаетесь достать их синхронно...