I have a Flutter Text widget and its content is populated from an external REST call.I would like to refresh the widget content periodically every 5 mins by calling the REST endpoint.
So far I managed to call the endpoint every 5 mins but unable to update/refresh the widget content with new data from network.
class PatientCount {
int count;
double amount;
PatientCount({this.count, this.amount});
PatientCount.fromJson(Map<String, dynamic> map)
: count = map['count'],
amount = map['amount'];
}
Future<PatientCount> fetchPatientCount() async {
var url = "http://localhost:9092/hms/patients-count-on-day";
Map<String, String> requestHeaders = new Map<String, String>();
requestHeaders["Accept"] = "application/json";
requestHeaders["Content-type"] = "application/json";
String requestBody = '{"consultedOn":' + '16112018' + '}';
http.Response response =
await http.post(url, headers: requestHeaders, body: requestBody);
final statusCode = response.statusCode;
final Map responseBody = json.decode(response.body);
if (statusCode != 200 || responseBody == null) {
throw new FetchPatientCountException(
"Error occured : [Status Code : $statusCode]");
}
return PatientCount.fromJson(responseBody['responseData'].
['PatientCountDTO']);
}
class MainPage extends StatefulWidget {
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
#override
void initState() {
super.initState();
setState(() {
const oneSecond = const Duration(seconds: 25);
new Timer.periodic(oneSecond, (Timer t) => buildCountWidget());
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 2.0,
backgroundColor: Colors.white,
title: Text('Dashboard'),
),
body: StaggeredGridView.count(
crossAxisCount: 2,
crossAxisSpacing: 12.0,
mainAxisSpacing: 12.0,
padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
children: <Widget>[
_buildTile(
Padding(
padding: const EdgeInsets.all(24.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Today\'s OPD',
style: TextStyle(
color: Colors.blueAccent, fontSize: 18.0),
),
buildCountWidget(),
],
),
Material(
color: Colors.blue,
borderRadius: BorderRadius.circular(24.0),
child: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Icon(Icons.timeline,
color: Colors.white, size: 30.0),
)))
]),
),
),
],
staggeredTiles: [StaggeredTile.extent(2, 110.0)],
));
}
Widget _buildTile(Widget child, {Function() onTap}) {
return Material(
elevation: 14.0,
borderRadius: BorderRadius.circular(12.0),
shadowColor: Color(0x802196F3),
child: InkWell(
// Do onTap() if it isn't null, otherwise do print()
onTap: onTap != null
? () => onTap()
: () {
print('Not set yet');
},
child: child));
}
Widget buildCountWidget() {
Widget vistitCount = new Center(
child: new FutureBuilder<PatientCount>(
future: fetchPatientCount(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
print(snapshot.data.count);
/* below text needs to be updated every 5 mins or so */
return new Text('#' + snapshot.data.count.toString(),
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 34.0));
} else if (snapshot.hasError) {
return new Text("${snapshot.error}");
}
}
// By default, show a loading spinner
return new CircularProgressIndicator();
},
),
);
return vistitCount;
}
}
Inside the buildCountWidget method the Text widget needs to be refreshed with the latest data from the network.
I changed the implementation to use setState as below, still no luck
class _MainPageState extends State<MainPage> {
Future<PatientCount> _patientCount;
Timer timer;
#override
void initState() {
super.initState();
callApi();
timer = Timer.periodic(Duration(seconds: 15), (Timer t) => setState(() {}));
}
void callApi() {
setState(() {
_patientCount = fetchPatientCount();
});
}
..........................
Also changed the logic as below, with this I am able to call the REST endpoint but the widget data is not getting updated every 25 seconds.The widget is showing the old data .
class _MainPageState extends State<MainPage> {
Future<PatientCount> _patientCount;
Timer timer;
#override
void initState() {
super.initState();
//callApi();
timer = Timer.periodic(Duration(seconds: 15), (Timer t) => callApi());
}
void callApi() {
setState(() {
_patientCount = fetchPatientCount();
});
}
...........................
As per the code it is showing the same count , the count is not getting incremented after 25 seconds.However from the backend the Api is fired periodically and returning the data to UI, but the state to the widget is not changing.
Replace this :
new Timer.periodic(oneSecond, (Timer t) => buildCountWidget());
By this:
new Timer.periodic(oneSecond, (Timer t) => setState((){}));
And it should work, every time you call setState it'll refresh the widget and will call to the Future method again.
UPDATE
It's working fine, if you make these changes, you will notice how the data is refreshed (just for testing):
Future<String> fetchPatientCount() async {
print("fetchPatientCount");
return DateTime.now().toIso8601String();
}
...
new FutureBuilder<String>(
future: fetchPatientCount(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
/* below text needs to be updated every 5 mins or so */
return new Text('#' + snapshot.data.toString(),
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize:7.0));
} else if (snapshot.hasError) {
return new Text("${snapshot.error}");
}
}
If the data changes every 25 seconds, it's working , you have to check your fetchPatientCount method. ( encode the data to json before send requestBody)
Related
in my implementation Bloc pattern i can get some data from server like with name and email, i can show this data with separated widget in layout such as show name with Text, as i have some widget in layout such as
Text('Hi $_username')
before getting data from server i want to try update this variable after getting data from server
for example:
class Login extends StatefulWidget {
final LoginListingBloc loginListingBloc;
Login({this.loginListingBloc});
State<Login> createState() {
return _Login(loginListingBloc: loginListingBloc);
}
}
class _Login extends State<Login> {
var _userPageName='';
_Login({this.loginListingBloc});
final LoginListingBloc loginListingBloc;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
Padding(
padding: EdgeInsets.only(bottom: 50.0),
child: SingleChildScrollView(
child: Container(
...child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"welcome $_userPageName",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600),
),
...
],
)),
Row(
children: <Widget>[
...
IconButton(
icon: new Icon(Icons.account_circle),
onPressed: () {
loginListingBloc.dispatch(LoginEvent(loginInfoModel: testLogin));
},
iconSize: 40.0,
color: Colors.white,
),
],
),
),
],
),
LoginListing()
],
)),
),
)
],
),
);
}
}
class LoginListing extends StatelessWidget {
#override
Widget build(BuildContext context) {
return BlocBuilder(
bloc: BlocProvider.of<LoginListingBloc>(context),
builder: (context, state) {
if (state is LoginUninitializedState) {
return Message(
message: 'login is not available',
);
} else if (state is LoginFetchingState) {
return Expanded(
child: CircularProgressIndicator(),
);
} else if (state is LoginErrorState) {
return Message(message: 'Error');
} else {
final stateAsLoginFetchedState = state as LoginFetchedState;
final loginInfo = stateAsLoginFetchedState.userInfo;
return buildShowLoginInfoItems(loginInfo);
}
});
}
Widget buildShowLoginInfoItems(UserInfo userInfo) {
return Container(
child: Text(userInfo.name),
);
}
}
in that how can i update $_userPageName after click on IconButton?
my LoginListingBloc implemented class:
class LoginListingBloc extends Bloc<LoginListingEvent, LoginListingStates> {
final LoginRepository loginRepository;
LoginListingBloc({this.loginRepository});
#override
LoginListingStates get initialState => LoginUninitializedState();
#override
Stream<LoginListingStates> mapEventToState(
LoginListingStates currentState, LoginListingEvent event) async* {
if (event is LoginEvent) {
yield LoginFetchingState();
try {
final loginInfo = await loginRepository.fetchLoginToPage(
event.loginInfoModel.username, event.loginInfoModel.password);
yield LoginFetchedState(userInfo: loginInfo);
} catch (_) {
yield LoginErrorState();
}
}
}
}
I am trying to use shared preference in my app with the bloc pattern.
Following is my code
class PrefsStats {
final bool isMale;
final String name;
final int age;
PrefsStats(this.isMale, this.name, this.age);
}
class PrefsBloc {
final _changePrefernce = BehaviorSubject<PrefsStats>();
Function(PrefsStats) get changePrefs => _changePrefernce.sink.add;
Stream<PrefsStats> get prefrence => _changePrefernce.stream;
SharedPreferences sPrefs;
dispose(){
_changePrefernce?.close();
}
PrefsBloc(){
_loadSharedPreferences();
}
Future<void> _loadSharedPreferences() async {
sPrefs = await SharedPreferences.getInstance();
final namePref = sPrefs.getString("name") ?? "";
final malePref = sPrefs.getBool("male") ?? false;
final agePref = sPrefs.getInt("age") ?? 0;
_changePrefernce.add(PrefsStats(malePref,namePref,agePref));
}
}
final prefsBloc = PrefsBloc();
I just want to insert data using one button and get data using another button from SharedPreferences
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
SizedBox(
height: 20,
),
RaisedButton(
onPressed: () {
prefsBloc.changePrefs(PrefsStats(true, "argo", 21));
},
child: Text("Insert Data"),
),
SizedBox(
height: 20,
),
RaisedButton(
onPressed: () {
prefsBloc.prefrence.forEach((data){
print(data.name);
});
},
child: Text("Get Data"),
),
SizedBox(
height: 20,
),
],
)),
),
);
}
#override
void dispose() {
prefsBloc?.dispose();
super.dispose();
}
}
Whenever I close my app and reopen it again and I click get data button at the start even before inserting data, I get default values. I know I am not assigning keys at the time of setting value, which is causing the confusion of how to use shared preferences with bloc. And the other problem is whenever I set data, the code inside get data button gets called even before pressing get data which I fail to understand.
There exits two places on your code that must be fixed.
First of all, in your BloC class, your stream must Listen whenever a sink is added,
.
.
.
PrefsBloc(){
_loadSharedPreferences();
_changePrefernce.stream.listen(_newFunction);
}
void _newFunction(PrefsStats stats){
if (states != null) {
if (sPrefs != null) {
sPrefs.setString("name", states.name);
sPrefs.setInt("age", states.age);
sPrefs.setBool("male", states.isMale);
sPrefs.commit();
}
}
}
Second place is in _MyAppState class, in the build function you have to wrap Scaffold with a StreamBuilder,
class _MyHomePageState extends State<MyHomePage> {
String textAge = "";
#override
Widget build(BuildContext context) {
return MaterialApp(
home: StreamBuilder(
stream: prefsBloc.prefrence,
builder: (context, AsyncSnapshot<PrefsStats> snapshot) {
return Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
Text((snapshot.data != null) ? snapshot.data.name : ""),
SizedBox(
height: 20,
),
RaisedButton(
onPressed: () {
prefsBloc.changePrefs(PrefsStats(
true,
textAge.toString(),
21,
));
},
child: Text("Insert Data"),
),
TextFormField(
initialValue: (snapshot.data != null) ? snapshot.data.name : "",
onFieldSubmitted: (value) {
textAge = value;
},
),
Text(textAge),
SizedBox(
height: 20,
),
RaisedButton(
onPressed: () {
prefsBloc.prefrence.forEach((data) {
print(data.name);
setState(() {
textAge = data.name;
});
});
},
child: Text("Get Data"),
),
SizedBox(
height: 20,
),
],
)),
);
},
));
}
I am working on a flutter widget which needs to load and update data in a Text with rest call. async call fetchPatientCount brings the data from REST resource and update the counter inside the setState method.
As a result of the below implementation, since the build method called twice, the counter value is NULL for the first time and causing the below exception.However for the second time the value is being populated.
flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building MainPage(dirty, state: _MainPageState#9e9d8):
flutter: 'package:flutter/src/widgets/text.dart': Failed assertion: line 235 pos 15: 'data != null': is not
flutter: true.
Any help will be appreciated related to the issue.
class MainPage extends StatefulWidget {
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
String counter;
#override
void initState() {
super.initState();
fetchPatientCount().then((val) {
setState(() {
counter = val.count.toString();
});
});
}
#override
Widget build(BuildContext context) {
String text;
if(counter!=null) {
text = counter;
}
return Scaffold(
appBar: AppBar(
elevation: 2.0,
backgroundColor: Colors.white,
title: Text('Dashboard',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 30.0)),
),
body: StaggeredGridView.count(
crossAxisCount: 2,
crossAxisSpacing: 12.0,
mainAxisSpacing: 12.0,
padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
children: <Widget>[
_buildTile(
Padding(
padding: const EdgeInsets.all(24.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Total Views',
style: TextStyle(color: Colors.blueAccent)),
Text(text,/* Here text is NULL for the first time */
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 34.0))
],
),
Material(
color: Colors.blue,
borderRadius: BorderRadius.circular(24.0),
child: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Icon(Icons.timeline,
color: Colors.white, size: 30.0),
)))
]),
),
),
],
staggeredTiles: [StaggeredTile.extent(2, 110.0)],
));
}
Widget _buildTile(Widget child, {Function() onTap}) {
return Material(
elevation: 14.0,
borderRadius: BorderRadius.circular(12.0),
shadowColor: Color(0x802196F3),
child: InkWell(
// Do onTap() if it isn't null, otherwise do print()
onTap: onTap != null
? () => onTap()
: () {
print('Not set yet');
},
child: child));
}
}
class PatientCount {
int count;
double amount;
PatientCount({this.count, this.amount});
PatientCount.fromJson(Map<String, dynamic> map)
: count = map['count'],
amount = map['amount'];
}
Future<PatientCount> fetchPatientCount() async {
var url = "http://localhost:9092/hms/patients-count-on-day";
Map<String, String> requestHeaders = new Map<String, String>();
requestHeaders["Accept"] = "application/json";
requestHeaders["Content-type"] = "application/json";
String requestBody = '{"consultedOn":' + '16112018' + '}';
http.Response response =
await http.post(url, headers: requestHeaders, body: requestBody);
final statusCode = response.statusCode;
final Map responseBody = json.decode(response.body);
if (statusCode != 200 || responseBody == null) {
throw new Exception(
"Error occured : [Status Code : $statusCode]");
}
return PatientCount.fromJson(responseBody['responseData']['PatientCountDTO']);
}
I solved my self, used FutureBuilder to resolve the issue.
Here is the full code below.
class PatientCount {
int count;
double amount;
PatientCount({this.count, this.amount});
PatientCount.fromJson(Map<String, dynamic> map)
: count = map['count'],
amount = map['amount'];
}
Future<PatientCount> fetchPatientCount() async {
var url = "http://localhost:9092/hms/patients-count-on-day";
Map<String, String> requestHeaders = new Map<String, String>();
requestHeaders["Accept"] = "application/json";
requestHeaders["Content-type"] = "application/json";
String requestBody = '{"consultedOn":' + '16112018' + '}';
http.Response response =
await http.post(url, headers: requestHeaders, body: requestBody);
final statusCode = response.statusCode;
final Map responseBody = json.decode(response.body);
if (statusCode != 200 || responseBody == null) {
throw new FetchPatientCountException(
"Error occured : [Status Code : $statusCode]");
}
return PatientCount.fromJson(responseBody['responseData']['PatientCountDTO']);
}
class MainPage extends StatefulWidget {
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 2.0,
backgroundColor: Colors.white,
title: Text('Dashboard',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 30.0)),
),
body: StaggeredGridView.count(
crossAxisCount: 2,
crossAxisSpacing: 12.0,
mainAxisSpacing: 12.0,
padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
children: <Widget>[
_buildTile(
Padding(
padding: const EdgeInsets.all(24.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Total Views',
style: TextStyle(color: Colors.blueAccent)),
/*Text(get,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 34.0))*/
buildCountWidget()
],
),
Material(
color: Colors.blue,
borderRadius: BorderRadius.circular(24.0),
child: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Icon(Icons.timeline,
color: Colors.white, size: 30.0),
)))
]),
),
),
],
staggeredTiles: [StaggeredTile.extent(2, 110.0)],
));
}
Widget _buildTile(Widget child, {Function() onTap}) {
return Material(
elevation: 14.0,
borderRadius: BorderRadius.circular(12.0),
shadowColor: Color(0x802196F3),
child: InkWell(
// Do onTap() if it isn't null, otherwise do print()
onTap: onTap != null
? () => onTap()
: () {
print('Not set yet');
},
child: child));
}
Widget buildCountWidget() {
Widget vistitCount = new Center(
child: new FutureBuilder<PatientCount>(
future: fetchPatientCount(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return new Text(snapshot.data.count.toString(),
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 34.0));
} else if (snapshot.hasError) {
return new Text("${snapshot.error}");
}
// By default, show a loading spinner
return new CircularProgressIndicator();
},
),
);
return vistitCount;
}
}
If it's null, build a widget that says that it's loading. It will build the actual widgets in the second call that you mentioned.
Basically, do this:
#override
Widget build(BuildContext context) {
String text;
if(counter!=null) {
text = counter;
} else {
return Text("loading..."); // or a fancier progress thing
}
fetchPatientCount().then((val) {
setState(() {
counter = val.count.toString();
});
});
That's expected behavior. "async" means the result will be available eventually later and then the code passed to then will be executed.
Flutter doesn't wait for that. It calls build() for every frame.
Perhaps you wanted to change
if(counter!=null) {
text = counter;
}
to
if(counter!=null) {
text = counter;
} else {
text = 'waiting ...';
}
because otherwise text will be null and Text(null) causes the error you got.
I'm trying to create a preferences menu where I have three settings (e. g. 'notifications') stored with Shared Preferences. They are applied to SwitchListTiles.
Everytime my settings tab is selected there is an error (I/flutter (22754): Another exception was thrown: 'package:flutter/src/material/switch_list_tile.dart': Failed assertion: line 84 pos 15: 'value != null': is not true.) appearing just a millisecond. After that the correct settings are displayed. This happens when I don't add a default value to the variables initialized in 'ProfileState'. If they have a default value the error disappears but the switches are 'flickering' at tab selection from the default value to the correct value in Shared Preferences.
My assumption is that my loadSettings function is executed after the build method.
How can I solve that? Any help is appreciated.
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Profile extends StatefulWidget {
#override
ProfileState createState() {
return new ProfileState();
}
}
class ProfileState extends State<Profile> {
bool notifications;
bool trackHistory;
bool instantOrders;
#override
void initState() {
super.initState();
loadSettings();
}
//load settings
loadSettings() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
notifications = (prefs.getBool('notifications') ?? true);
trackHistory = (prefs.getBool('trackHistory') ?? true);
instantOrders = (prefs.getBool('instantOrders') ?? false);
});
}
//set settings
setSettings() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('notifications', notifications);
prefs.setBool('trackHistory', trackHistory);
prefs.setBool('instantOrders', instantOrders);
}
#override
Widget build(BuildContext context) {
return new ListView(
children: <Widget>[
new Row(
children: <Widget>[
new Container(
padding: new EdgeInsets.fromLTRB(20.0, 20.0, 0.0, 8.0),
child: new Text("General", style: new TextStyle(color: Colors.black54)),
)
],
),
new SwitchListTile(
title: const Text('Receive Notifications'),
activeColor: Colors.brown,
value: notifications,
onChanged: (bool value) {
setState(() {
notifications = value;
setSettings();
});
},
secondary: const Icon(Icons.notifications, color: Colors.brown),
),
new SwitchListTile(
title: const Text('Track History of Orders'),
activeColor: Colors.brown,
value: trackHistory,
onChanged: (bool value) {
setState((){
trackHistory = value;
setSettings();
});
},
secondary: const Icon(Icons.history, color: Colors.brown,),
),
new SwitchListTile(
title: const Text('Force instant Orders'),
activeColor: Colors.brown,
value: instantOrders,
onChanged: (bool value) {
setState((){
instantOrders = value;
setSettings();
});
},
secondary: const Icon(Icons.fast_forward, color: Colors.brown),
),
new Divider(
height: 10.0,
),
new Container(
padding: EdgeInsets.all(32.0),
child: new Center(
child: new Column(
children: <Widget>[
new TextField(
)
],
),
),
),
new Divider(
height: 10.0,
),
new Row(
children: <Widget>[
new Container(
padding: new EdgeInsets.fromLTRB(20.0, 20.0, 0.0, 20.0),
child: new Text("License Information", style: new TextStyle(color: Colors.black54)),
)
],
),
new Container(
padding: new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 20.0) ,
child: new RichText(
text: new TextSpan(
text: "With confirming our terms and conditions you accept full usage of your personal data. Yikes!",
style: new TextStyle(color: Colors.black)
)
)
)
]
);
}
}
EDIT
I tried to solve it with the recommended FutureBuilder from Darek's solution. The initial error is solved now but now I face another inconvenience. The tab builds itself completely everytime a switch is tapped which is clearly noticable. Furthermore the switches don't run smoothly anymore. On startup of the app you can also see the waiting message shortly which isn't that pretty.
Here is the new class in the code:
class ProfileState extends State<Profile> {
bool notifications;
bool trackHistory;
bool instantOrders;
SharedPreferences prefs;
#override
void initState() {
super.initState();
loadSettings();
}
//load settings
Future<String> loadSettings() async {
prefs = await SharedPreferences.getInstance();
notifications= (prefs.getBool('notifications') ?? true);
trackHistory = (prefs.getBool('trackHistory') ?? true);
instantOrders= (prefs.getBool('instantOrders') ?? true);
}
//set settings
setSettings() async {
prefs.setBool('notifications', notifications);
prefs.setBool('trackHistory', trackHistory);
prefs.setBool('instantOrders', instantOrders);
}
#override
Widget build(BuildContext context) {
var profileBuilder = new FutureBuilder(
future: loadSettings(), // a Future<String> or null
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return new Text('No preferences');
case ConnectionState.waiting:
return new Text('Loading preferences');
case ConnectionState.done:
if (snapshot.hasError)
return new Text('Error: ');
else
return new Column(
children: <Widget>[
new Row(
children: <Widget>[
new Container(
padding: new EdgeInsets.fromLTRB(20.0, 20.0, 0.0, 8.0),
child: new Text("General", style: new TextStyle(color: Colors.black54)),
)
],
),
new SwitchListTile(
title: const Text('Receive Notifications'),
activeColor: Colors.brown,
value: notifications,
onChanged: (bool value) {
setState(() {
notifications = value;
setSettings();
});
},
secondary: const Icon(Icons.notifications, color: Colors.brown),
),
new SwitchListTile(
title: const Text('Track History of Orders'),
activeColor: Colors.brown,
value: trackHistory,
onChanged: (bool value) {
setState((){
trackHistory = value;
setSettings();
});
},
secondary: const Icon(Icons.history, color: Colors.brown,),
),
new SwitchListTile(
title: const Text('Force instant Orders'),
activeColor: Colors.brown,
value: instantOrders,
onChanged: (bool value) {
setState((){
instantOrders = value;
setSettings();
});
},
secondary: const Icon(Icons.fast_forward, color: Colors.brown),
),
new Divider(
height: 10.0,
),
new Row(
children: <Widget>[
new Container(
padding: new EdgeInsets.fromLTRB(20.0, 20.0, 0.0, 20.0),
child: new Text("License Information", style: new TextStyle(color: Colors.black54)),
)
],
),
new Container(
padding: new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 20.0) ,
child: new RichText(
text: new TextSpan(
text: "With confirming our terms and conditions you accept full usage of your personal data. Yikes!",
style: new TextStyle(color: Colors.black)
)
)
)
]
);
}
},
);
return new Scaffold(
body: profileBuilder,
);
}
}
The lifecycle of a State object goes createState -> initState -> didChangeDependencies -> build (see the linked doc for more details). So in your case it's not an ordering problem. What's actually happening is that loadSettings is getting called, but as soon as it hits the await a Future is return and execution of the caller continues (see async/await in the Dart docs). So, your widget tree is being built and your initially null values are being used, then the async part gets executed and your variables are initialised and setState is called triggering the rebuild, which works fine.
What you need to use is a FutureBuilder so that you can build the UI accordingly when the Future has finished:
new FutureBuilder(
future: _calculation, // a Future<String> or null
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none: return new Text('Press button to start');
case ConnectionState.waiting: return new Text('Awaiting result...');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return new Text('Result: ${snapshot.data}');
}
},
)
In the above example, you'd replace _calculation with loadSettings and return the relevant UIs in the none and waiting states (the latter will be your one with the SwitchListTiles).
To fix the problem of your Edit, store the Future from the loadSettings call in your initState and use this Future for the Future Builder. What you are doing now is calling the function loadSettings everytime your UI rebuilds.
class ProfileState extends State<Profile> {
bool notifications;
bool trackHistory;
bool instantOrders;
SharedPreferences prefs;
Future<String> loadSettingsFuture; // <-Add this
#override
void initState() {
super.initState();
loadSettingsFuture = loadSettings();// <- Change This
}
...
...
...
#override
Widget build(BuildContext context) {
var profileBuilder = new FutureBuilder(
future: loadSettingsFuture, // <-- Change this
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
...
...
I have a FutureBuilder that gets DISTINCT dates from a local sqlite DB, then I take each date and get the messages for those dates to put them in the widget, this works fine, until you want to listen realtime to a stream or poll for new messages which rebuilds the widgets and flickers the page and then scrolls to the beginning each time. I am hoping to find a way to take all the data into some object or other widget and then group by date and order, etc.. This way I can listen to a stream for updated messages, etc..
Any help would be great, here is my code if it helps anyone see what I do, this is after I converted to Streambuilder, but same result.
new StreamBuilder(
initialData: myInitialData,
stream: msgstream,
builder: (BuildContext context, AsyncSnapshot<List<Map>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return new Text('Waiting to start');
case ConnectionState.waiting:
return new Text('');
default:
if (snapshot.hasError) {
return new Text('Error: ${snapshot.error}');
} else {
myInitialData = snapshot.data;
return new RefreshIndicator(
child: new ListView.builder(
itemBuilder: (context, index) {
return new MyChatWidget(
datediv: snapshot.data[index]['msgdate'],
msgkey: snapshot.data[index]['msgkey'],
);
},
//itemBuilder: _itemBuilder,
controller: _scrollController,
reverse: true,
itemCount: snapshot.data.length,
),
onRefresh: _onRefresh
);
}
}
}),
This is the Widget that the StreamBuilder calls:
class MyChatWidget extends StatefulWidget {
MyChatWidget({Key key, this.datediv, this.msgkey}) : super(key: key);
final String datediv;
final String msgkey;
#override
_MyChatWidgetState createState() => new _MyChatWidgetState();
}
class _MyChatWidgetState extends State<MyChatWidget> {
List<Widget> messagelist;
int messagecount = 0;
var jsonCodec = const JsonCodec();
var mydate = '';
var _urlMessages = '';
PageStorageKey _key;
VideoPlayerController vcontroller;
//Future<http.Response> _responseFuture;
Future<List<Map>> _responseFuture;
List messList;
var mybytes;
File myimageview;
Image newimageview;
String imgStr;
String vidStr;
String vidimgstr;
bool submitting = false;
List<Map> myInitialData;
Stream<List<Map>> msgstream;
#override
void initState() {
super.initState();
if (new DateFormat.yMd().format(DateTime.parse(widget.datediv)) ==
new DateFormat.yMd().format(new DateTime.now())) {
mydate = 'Today';
} else {
mydate = new DateFormat.yMMMEd().format(DateTime.parse(widget.datediv));
}
DateChatMessage dcm =
new DateChatMessage(widget.msgkey, widget.datediv.toString());
var json = jsonCodec.encode(dcm);
_urlMessages =
'http://loop-dev.clinicalsoftworks.com/chat/messages/getbydate';
//_responseFuture = http.post(_urlMessages, body: json, headers: getAuthHeader());
_responseFuture =
ChatDB.instance.getMessagesByDate(widget.msgkey, widget.datediv);
msgstream = new Stream.fromFuture(_responseFuture);
//controller = new TabController(length: 4, vsync: this);
//_getMessages();
}
/*#override
void dispose() {
super.dispose();
if (vcontroller != null) {
vcontroller.dispose();
}
}*/
#override
Widget build(BuildContext context) {
_key = new PageStorageKey('${widget.datediv.toString()}');
return new Column(
children: <Widget>[
new Container(
child: new Text(
mydate,
textAlign: TextAlign.left,
style: new TextStyle(
color: Colors.grey,
fontWeight: FontWeight.bold,
),
),
alignment: Alignment.centerLeft,
padding: new EdgeInsets.only(left: 10.0),
),
new Container(
child: new Divider(
height: 5.0,
color: Colors.grey,
),
padding: new EdgeInsets.only(left: 10.0, right: 10.0),
),
/**/
new StreamBuilder(
initialData: myInitialData,
stream: msgstream,
builder: (BuildContext context, AsyncSnapshot<List<Map>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return new Text('Waiting to start');
case ConnectionState.waiting:
return new Text('');
default:
myInitialData = snapshot.data;
List<dynamic> json = snapshot.data;
messagelist = [];
json.forEach((element) {
DateTime submitdate =
DateTime.parse(element['submitdate']).toLocal();
String myvideo = (element['chatvideo']);
String myimage = element['chatimage'];
String myvideoimage = element['chatvideoimage'];
File imgfile;
File vidfile;
File vidimgfile;
bool vidInit = false;
Future<Null> _launched;
String localAssetPath;
String localVideoPath;
String mymessage = element['message'].replaceAll("[\u2018\u2019]", "'");
//print('MYDATE: '+submitdate.toString());
_checkFile(File file) async {
var checkfile = await file.exists();
print('VIDEXISTS: '+checkfile.toString());
}
Future<Null> _launchVideo(String url, bool isLocal) async {
if (await canLaunchVideo(url, isLocal)) {
await launchVideo(url, isLocal);
} else {
throw 'Could not launch $url';
}
}
void _launchLocal() =>
setState(() => _launched = _launchVideo(localVideoPath, true)
);
Widget _showVideo() {
/*return new Flexible(
child: new vplayer.VideoCard(
controller: vcontroller,
title: element['referralname'],
subtitle: 'video',
),
);*/
return new Flexible(
child: new Card(
child: new Column(
children: <Widget>[
new ListTile(subtitle: new Text('Video'), title: new Text(element['referralname']),),
new GestureDetector(
onTap: _launchLocal,
child: new Image.file(
vidimgfile,
width: 150.0,
),
),
],
),
)
);
}
_initVideo() {
setState(() {vidInit = true;});
}
_onError() {
print('VIDEO INIT ERROR');
}
if (myimage != "") {
imgStr = element['chatimage'];
imgfile = new File(imgStr);
}
if (myvideo != "") {
vidStr = element['chatvideo'];
vidimgstr = element['chatvideoimage'];
vidimgfile = new File(vidimgstr);
//vidfile = new File(vidStr);
//_checkFile(vidfile);
//print('vidfile: '+vidfile.path);
localVideoPath = '$vidStr';
//print('LOCALVIDEO: '+localVideoPath);
//vcontroller = new VideoPlayerController('file://$vidStr')..initialize();
}
_showLgPic() {
Route route = new MaterialPageRoute(
settings: new RouteSettings(name: "/ShowPic"),
builder: (BuildContext context) => new ShowPic(
image: imgfile,
),
);
Navigator.of(context).push(route);
}
Widget _showGraphic() {
Widget mywidget;
if (myimage != "") {
mywidget = new GestureDetector(
child: new Image.file(
imgfile,
width: 300.0,
),
onTap: _showLgPic,
);
} else if (myvideo != "") {
mywidget = _showVideo();
} else {
mywidget = new Container();
}
return mywidget;
}
messagelist.add(
new Container(
//width: 300.0,
padding: new EdgeInsets.all(10.0),
child: new Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new Container(
padding: new EdgeInsets.only(bottom: 5.0),
child: new Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new CircleAvatar(
child: new Text(
element['sendname'][0],
style: new TextStyle(fontSize: 15.0),
),
radius: 12.0,
),
new Text(' '),
new Text(
element['sendname'],
style: new TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.bold),
),
new Text(' '),
new Text(
new DateFormat.Hm().format(submitdate),
style: new TextStyle(
color: Colors.grey, fontSize: 12.0),
),
],
),
),
new Row(
children: <Widget>[
new Text(' '),
new Flexible(
child: new Text(mymessage),
)
],
),
new Container(
width: 150.0,
child: new Row(
children: <Widget>[
new Text(' '),
_showGraphic()
/*myimage != ""
? new GestureDetector(
child: new Image.file(
imgfile,
width: 300.0,
),
onTap: _showLgPic,
)
: myvideo != "" ? _showVideo() : new Container(),*/
],
)),
],
),
),
);
});
return new Column(children: messagelist);
}
},
)
],
);
}
}
Thanks for any assistance
which rebuilds the widgets and flickers the page and then scrolls to the beginning each time
To solve problem with scrolling try ScrollController. Create your own, keep it between updates and inject into List you created.
To solve flickering you could use Key for List widgets. Key should be unique identifier of message, e.g. msgkey
This example how to keep scrolloffset works for me
class SomeWidget extends StatefulWidget {
#override
_SomeWidgetState createState() => new _SomeWidgetState();
}
class _SomeWidgetState extends State<SomeWidget> {
ScrollController _scrollController;
int _count;
#override
void initState() {
super.initState();
_count = 10;
_scrollController = new ScrollController();
}
void _add() {
setState(() => _count += 5);
}
#override
Widget build(BuildContext context) {
final _titles = new List<String>.generate(_count, (i) => 'Title ${i}');
return new Scaffold(
appBar: new AppBar(
title: new Text("Demo"),
actions: <Widget>[
new IconButton(icon: new Icon(Icons.add), onPressed: _add)
],
),
body: new ListView.builder(
controller: _scrollController,
itemCount: _titles.length,
itemBuilder: (context, index) => new ListTile(
title: new Text(_titles[index]),
),
),
);
}
}