ListView isnt updating state after I added a FutureBuilder - dart

Before this problem happen I was dealing with Future handling to return the values I saved on a sharedPreference, however my _deleteTodo method was working just fine.
After I added the FutureBuilder and finally got my values rendered on the UI now I'm struggling with this new bug.
Every time I update the state of and item my UI reflects it but immediately undoes it
I tried to see if it was something with my _deleteTodo method so I changed the setState to only change the boolean from false to true, but it does exactly the same.
I also print the length of my List after the _deleteTodo and something funny happens: it works one time, the _deleteTodo erase the Todo but after that it doesn't work anymore
This is my TODO class
class Todo {
Todo ({this.title,this.isDone = false});
String title;
bool isDone;
//Decode method to convert a Json String into a Dynamic object
Todo.fromJson(Map <String, dynamic> json)
: title = json ["title"],
isDone = json ["isDone"];
Map <String,dynamic> toJson() =>
{
"title" : title,
"isDone" : isDone
};
}
This is my screen
class _TodoListScreenState extends State<TodoListScreen> {
List<Todo> todos = [];
//updates the state of the checkbox and reflects it on the UI
_toggleTodo(Todo todo, bool isChecked) {
setState(() {
todo.isDone = isChecked;
_deleteTodo(todo,isChecked);
print(todos.length);
});
}
_addTodo() async {
final todo = await showDialog<Todo>(
context: context,
builder: (BuildContext context) { // <- Here you draw the
Dialog
return NewTodoDialog();
},
);
if (todo != null) {
setState(() {
todos.add(todo);
_saveTodo(todos);
print(todos.length);
});
}
}
_deleteTodo (Todo todo, bool isDone) => (isDone)?
todos.remove(todo): debugPrint;
//Save you array object as an array of Strings in Shared Preferences
Future<void> _saveTodo(List<Todo> todo) async {
SharedPreferences sharedPreferences = await
SharedPreferences.getInstance();
sharedPreferences.setStringList("savedData", _mapTodoData(todo));
}
_mapTodoData(List<dynamic> todos) {
try {
var res = todos.map((v) => json.encode(v)).toList();
return res;
} catch (err) {
// Just in case
return ["Nope"];
}
}
Future<List> loadData() async {
SharedPreferences sharedPreferences = await
SharedPreferences.getInstance();
final List<Todo> todoArray =
_decodeTodoData(sharedPreferences.
getStringList("savedData")).toList();
todos = todoArray;
return todoArray;
}
List<Todo> _decodeTodoData(List<String> todos) {
try {
//Transforming List<String> to Json
var result = todos.map((v) => json.decode(v)).toList();
//Transforming the Json into Array<Todo>
var todObjects = result.map((v) => Todo.fromJson(v)).toList();
return todObjects;
} catch (error) {
return [];
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(backgroundColor: Colors.deepPurple[900],
title: Text('Todo List')),
body: Container(
child: FutureBuilder(
future: loadData(),
builder: (BuildContext context, AsyncSnapshot snapshot){
return TodoList(
todos: todos,
onTodoToggle: _toggleTodo,
);
})
)
,
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.purpleAccent[700],
child: Icon(Icons.add),
onPressed: _addTodo,
),
);
}
}
Thanks in advance, hope someone can help me :)

From what I can tell is that your _deleteTodo deletes from the local instance list todos but you are instructing flutter to rebuild the UI from disk via loadData which re-gets the data from disk.
My suggestion is to get the data once on page load using initState and from there only refer to the local instance of todos.
In your _deleteTodo you would also need to persist the state to disk or have a commit button somewhere

I Found the solution, inside my _toggleTodo i need it to save my TodoList after doing something to my todo.

Related

Flutter set startup page based on Shared Preference

I've been trying without success to load different pages according to my Shared Preference settings.
Based on several posts found in stackoverflow, i end up with the following solution:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:testing/screens/login.dart';
import 'package:testing/screens/home.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Widget page = Login();
Future getSharedPrefs() async {
String user = Preferences.local.getString('user');
if (user != null) {
print(user);
this.page = Home();
}
}
#override
void initState() {
super.initState();
this.getSharedPrefs();
}
#override
Widget build(BuildContext context) {
return MaterialApp(home: this.page);
}
}
class Preferences {
static SharedPreferences local;
/// Initializes the Shared Preferences and sets the info towards a global variable
static Future init() async {
local = await SharedPreferences.getInstance();
}
}
The variable user is not null because the print(user) returns a value as expected, but the login screen is always being opened.
Your problem is that your build method returns before your getSharedPrefs future is complete. The getSharedPrefs returns instantly as soon as it's called because it's async and you're treating it as a "Fire and Forget" by not awaiting. Seeing that you can't await in your initState function that makes sense.
This is where you want to use the FutureBuilder widget. Create a Future that returns a boolean (or enum if you want more states) and use a future builder as your home child to return the correct widget.
Create your future
Future<bool> showLoginPage() async {
var sharedPreferences = await SharedPreferences.getInstance();
// sharedPreferences.setString('user', 'hasuser');
String user = sharedPreferences.getString('user');
return user == null;
}
When user is null this will return true. Use this future in a Future builder to listen to the value changes and respond accordingly.
#override
Widget build(BuildContext context) {
return MaterialApp(home: FutureBuilder<bool>(
future: showLoginPage(),
builder: (buildContext, snapshot) {
if(snapshot.hasData) {
if(snapshot.data){
// Return your login here
return Container(color: Colors.blue);
}
// Return your home here
return Container(color: Colors.red);
} else {
// Return loading screen while reading preferences
return Center(child: CircularProgressIndicator());
}
},
));
}
I ran this code and it works fine. You should see a blue screen when login is required and a red screen when there's a user present. Uncomment the line in showLoginPage to test.
There is a much pretty way of doing this.
Assuming that you have some routes and a boolean SharedPreference key called initialized.
You need to use the WidgetsFlutterBinding.ensureInitialized() function before calling runApp() method.
void main() async {
var mapp;
var routes = <String, WidgetBuilder>{
'/initialize': (BuildContext context) => Initialize(),
'/register': (BuildContext context) => Register(),
'/home': (BuildContext context) => Home(),
};
print("Initializing.");
WidgetsFlutterBinding.ensureInitialized();
await SharedPreferencesClass.restore("initialized").then((value) {
if (value) {
mapp = MaterialApp(
debugShowCheckedModeBanner: false,
title: 'AppName',
theme: ThemeData(
primarySwatch: Colors.blue,
),
routes: routes,
home: Home(),
);
} else {
mapp = MaterialApp(
debugShowCheckedModeBanner: false,
title: 'AppName',
theme: ThemeData(
primarySwatch: Colors.blue,
),
routes: routes,
home: Initialize(),
);
}
});
print("Done.");
runApp(mapp);
}
The SharedPreference Class Code :
class SharedPreferencesClass {
static Future restore(String key) async {
final SharedPreferences sharedPrefs = await SharedPreferences.getInstance();
return (sharedPrefs.get(key) ?? false);
}
static save(String key, dynamic value) async {
final SharedPreferences sharedPrefs = await SharedPreferences.getInstance();
if (value is bool) {
sharedPrefs.setBool(key, value);
} else if (value is String) {
sharedPrefs.setString(key, value);
} else if (value is int) {
sharedPrefs.setInt(key, value);
} else if (value is double) {
sharedPrefs.setDouble(key, value);
} else if (value is List<String>) {
sharedPrefs.setStringList(key, value);
}
}
}

Could not launch Instance of 'Future<String>'

I have the following FutureBuilder function in class A:
Future<String> GetYoutubeLink() async{
var link = "";
CollectionReference collectionRef =
Firestore.instance.collection("r");
Query query = collectionRef.where('name',
isEqualTo: name).limit(1);
QuerySnapshot collectionSnapshot = await query.getDocuments().then((data){
if(data.documents.length > 0){
link = data.documents[0].data['link'];
print(link);
}
});
return link.toString();
}
}
I am trying to set the link in class B as follows:
class _B extends State<B> {
String link = null;
void initState(){
super.initState();
setState(() {
A a = new A(widget.dish_name);
if(link == null) {
link = a.GetYoutubeLink().toString();
}
});
}
#override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
icon: Icon(FontAwesomeIcons.youtubeSquare, size: 45,color:Colors.red),
onPressed: _launchURL,
),
],
);
}
_launchURL() async {
var url = link;
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
}
I am getting the following exception:
Could not launch Instance of 'Future'
Can someone tell me how to get the string instead of Future ?
Just Modify your code like this..
_launchURL() async{
CollectionReference collectionRef =
Firestore.instance.collection("r");
Query query = collectionRef.where('name',
isEqualTo: name).limit(1);
QuerySnapshot collectionSnapshot = await query.getDocuments().then((data){
if(data.documents.length > 0){
link = data.documents[0].data['link'];
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
});
}
And no need for initState() just remove that call.
Class a's method:
Future<String> getYoutubeLink() async {//its a good practice to set the method's name in lowerCamelCase
CollectionReference collectionRef = Firestore.instance.collection("r");
Query query = collectionRef.where('name', isEqualTo: name).limit(1);
QuerySnapshot collectionSnapshot = await query.getDocuments().then((data) {
try {
if (data.documents.length > 0) {
return data.documents[0].data['link'].toString(); //this will return the data as a string
}
} catch (e) {
return ""; //in case that something fails will return an empty string
}
});
return ""; //if it do not return anything will return an empty string
}
Class b:
class _B extends State<B> {
A a = new A(widget.dish_name);
#override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
icon: Icon(FontAwesomeIcons.youtubeSquare, size: 45,color:Colors.red),
onPressed: _launchURL,
),
],
);
}
_launchURL() async {
var url = await a.getYoutubeLink();//call here your method. You are useing 'await' because this methods returns a Future, it means that the execution of this function should take some time
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
}
Do not call Future methods inside your initState() because it would crash your app. If you need to call Future methods that need time to be completed before building your widget you can use the FutureBuilder widget. Check here the documentation.
To know more about Future and async programing watch this video by MTechViral. I have learned a lot from him!

Flutter Programmatically trigger FutureBuilder

Let's say I have something like this:
return FutureBuilder(
future: _loadingDeals,
builder: (BuildContext context, AsyncSnapshot snapshot) {
return RefreshIndicator(
onRefresh: _handleRefresh,
...
)
}
)
In the _handleRefresh method, I want to programmatically trigger the re-run of the FutureBuilder.
Is there such a thing?
The use case:
When a user pulls down the refreshIndicator, then the _handleRefresh simply makes the FutureBuilder rerun itself.
Edit:
Full code snippet end to end, without the refreshing part. I've switched to using the StreamBuilder, how will the refreshIndicator part fit in all of it?
class DealList extends StatefulWidget {
#override
State<StatefulWidget> createState() => new _DealList();
}
class _DealList extends State<DealList> with AutomaticKeepAliveClientMixin {
// prevents refreshing of tab when switch to
// Why? https://stackoverflow.com/q/51224420/1757321
bool get wantKeepAlive => true;
final RestDatasource api = new RestDatasource();
String token;
StreamController _dealsController;
#override
void initState() {
super.initState();
_dealsController = new StreamController();
_loadingDeals();
}
_loadingDeals() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
this.token = prefs.getString('token');
final res =
this.api.checkInterests(this.token).then((interestResponse) async {
_dealsController.add(interestResponse);
return interestResponse;
});
return res;
}
_handleRefresh(data) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final token = prefs.getString('token');
await this.api.checkInterests(token).then((interestResponse) {
_dealsController.add(interestResponse);
});
return null;
}
#override
Widget build(BuildContext context) {
super.build(context); // <-- this is with the wantKeepAlive thing
return StreamBuilder(
stream: _dealsController.stream,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
...
}
if (snapshot.connectionState != ConnectionState.done) {
return Center(
child: CircularProgressIndicator(),
);
}
if (!snapshot.hasData &&
snapshot.connectionState == ConnectionState.done) {
return Text('No deals');
}
if (snapshot.hasData) {
return ListView.builder(
physics: const AlwaysScrollableScrollPhysics(),
itemCount: snapshot.data['deals'].length,
itemBuilder: (context, index) {
final Map deal = snapshot.data['deals'][index];
return ListTile(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DealsDetailPage(
dealDetail: deal,
),
),
);
},
title: Text(deal['name']),
subtitle: Text(deal['expires']),
);
},
),
}
},
);
}
}
Why not using a StreamBuilder and a Stream instead of a FutureBuilder?
Something like that...
class _YourWidgetState extends State<YourWidget> {
StreamController<String> _refreshController;
...
initState() {
super...
_refreshController = new StreamController<String>();
_loadingDeals();
}
_loadingDeals() {
_refreshController.add("");
}
_handleRefresh(data) {
if (x) _refreshController.add("");
}
...
build(context) {
...
return StreamBuilder(
stream: _refreshController.stream,
builder: (BuildContext context, AsyncSnapshot snapshot) {
return RefreshIndicator(
onRefresh: _handleRefresh(snapshot.data),
...
)
}
);
}
}
I created a Gist with the Flutter main example using the StreamBuilder, check it out
Using StreamBuilder is a solution, however, to trigger the FutureBuilder programmatically, just call setState, it'll rebuild the Widget.
return RefreshIndicator(
onRefresh: () {
setState(() {});
},
...
)
I prefer FutureBuilder over StreamBuilder since I am using Firestore for my project and you get billed by reads so my solution was this
_future??= getMyFuture();
shouldReload(){
setState(()=>_future = null)
}
FutureBuilder(
future: _future,
builder: (context, snapshot){
return Container();
},
)
and any user activity that needs you to get new data simply call shouldReload()

Flutter Like button functionality using Futures

I'm trying to build a Save button that lets the user save/ unsave (like/ unlike) items displayed in a ListView.
What I have so far:
Repository that provides a Future<bool> that determines which state the icon should be rendered in
FutureBuilder that calls the repository and renders the icon as either saved/ unsaved.
Icon wrapped in a GestureDetector that makes a call to the repository within a setState call when onTap is invoked.
`
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: _repository.isSaved(item),
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
case ConnectionState.none:
case ConnectionState.active:
return Icon(Icons.favorite_border);
case ConnectionState.done:
return GestureDetector(
child: Icon(
snapshot.data ? Icons.favorite : Icons.favorite_border,
color: snapshot.data ? Colors.red : null),
onTap: () {
setState(() {
if (snapshot.data) {
_repository.removeItem(item);
} else {
_repository.saveItem(item);
}
});
},
);
}
});
}
`
The issue I'm having is that when I tap to save an item in the list - the item is saved however the icon is not updated until I scroll it off screen then back on again.
When I tap to unsave an item, it's state is reflected immediately and updates as expected.
I suspect that the save call is taking longer to complete than the delete call. Both of these are async operations:
void removeItem(String item) async {
_databaseClient.deleteItem(item);
}
void saveItem(String item) async {
_databaseClient.saveItem(item);
}
#override
void deleteItem(String item) async {
var client = await db;
client.delete("items_table", where: "item = '$item'"); // returns Future<int> but I'm not using this currently
}
void _saveItem(String item) async {
var client = await db;
client.insert("items_table", item); // returns Future<int> but I'm not using this currently
}
Future<bool> isSaved(String name) async {
var matching = await _databaseClient.getNameByName(name);
return matching != null && matching.isNotEmpty;
}
Any idea what could be causing this?
When you tap the button, setState will be called. then FutureBuilder will wait for the isSaved method. if the save method is being in progress. isSaved will return the last state and Icon will not change.
I suggest to wait for the result of Save and Remove method and call setState after that.
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: _repository.isSaved(item),
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
case ConnectionState.none:
case ConnectionState.active:
return Icon(Icons.favorite_border);
case ConnectionState.done:
return GestureDetector(
child: Icon(
snapshot.data ? Icons.favorite : Icons.favorite_border,
color: snapshot.data ? Colors.red : null),
onTap: () async{
if (snapshot.data) {
await _repository.removeItem(item);
} else {
await _repository.saveItem(item);
}
setState(() {
});
},
);
}
});
}
However, if the methods take so long, it delays which cause bad user experience. it better to change the icon to progress circle during running methods.

Flutter Reloading List with Streams & RxDart

I have one question regarding how to reload a list after refresh indicator is called in Flutter, using Streams and RxDart.
Here is what I have , my model class:
class HomeState {
List<Event> result;
final bool hasError;
final bool isLoading;
HomeState({
this.result,
this.hasError = false,
this.isLoading = false,
});
factory HomeState.initial() =>
new HomeState(result: new List<Event>());
factory HomeState.loading() => new HomeState(isLoading: true);
factory HomeState.error() => new HomeState(hasError: true);
}
class HomeBloc {
Stream<HomeState> state;
final EventRepository repository;
HomeBloc(this.repository) {
state = new Observable.just(new HomeState.initial());
}
void loadEvents(){
state = new Observable.fromFuture(repository.getEventList(1)).map<HomeState>((List<Event> list){
return new HomeState(
result: list,
isLoading: false
);
}).onErrorReturn(new HomeState.error())
.startWith(new HomeState.loading());
}
}
My widget:
class HomePageRx extends StatefulWidget {
#override
_HomePageRxState createState() => _HomePageRxState();
}
class _HomePageRxState extends State<HomePageRx> {
HomeBloc bloc;
_HomePageRxState() {
bloc = new HomeBloc(new EventRest());
bloc.loadEvents();
}
Future<Null> _onRefresh() async {
bloc.loadEvents();
return null;
}
#override
Widget build(BuildContext context) {
return new StreamBuilder(
stream: bloc.state,
builder: (BuildContext context, AsyncSnapshot<HomeState> snapshot) {
var state = snapshot.data;
return new Scaffold(
body: new RefreshIndicator(
onRefresh: _onRefresh,
child: new LayoutBuilder(builder:
(BuildContext context, BoxConstraints boxConstraints) {
if (state.isLoading) {
return new Center(
child: new CircularProgressIndicator(
backgroundColor: Colors.deepOrangeAccent,
strokeWidth: 5.0,
),
);
} else {
if (state.result.length > 0) {
return new ListView.builder(
itemCount: snapshot.data.result.length,
itemBuilder: (BuildContext context, int index) {
return new Text(snapshot.data.result[index].title);
});
} else {
return new Center(
child: new Text("Empty data"),
);
}
}
}),
),
);
});
}
}
The problem is when I do the pull refresh from list, the UI doesn't refresh (the server is called, the animation of the refreshindicator also), I know that the issue is related to the stream but I don't know how to solve it.
Expected result : Display the CircularProgressIndicator until the data is loaded
Any help? Thanks
You are not supposed to change the instance of state.
You should instead submit a new value to the observable. So that StreamBuilder, which is listening to state will be notified of a new value.
Which means you can't just have an Observable instance internally, as Observable doesn't have any method for adding pushing new values. So you'll need a Subject.
Basically this changes your Bloc to the following :
class HomeBloc {
final Stream<HomeState> state;
final EventRepository repository;
final Subject<HomeState> _stateSubject;
factory HomeBloc(EventRepository respository) {
final subject = new BehaviorSubject(seedValue: new HomeState.initial());
return new HomeBloc._(
repository: respository,
stateSubject: subject,
state: subject.asBroadcastStream());
}
HomeBloc._({this.state, Subject<HomeState> stateSubject, this.repository})
: _stateSubject = stateSubject;
Future<void> loadEvents() async {
_stateSubject.add(new HomeState.loading());
try {
final list = await repository.getEventList(1);
_stateSubject.add(new HomeState(result: list, isLoading: false));
} catch (err) {
_stateSubject.addError(err);
}
}
}
Also, notice how loadEvent use addError with the exception. Instead of pushing a HomeState with a hasError: true.

Resources