I am trying to add a widget to the screen when the future has data in Screen 1.
class UserChoiceBooks extends StatelessWidget {
final String title;
UserChoiceBooks({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: Provider.of<Books>(context, listen: false)
.getRecommendedBooks("test"),
builder: (ctx, snapshot) {
// Checking if future is resolved
if (snapshot.connectionState == ConnectionState.done) {
// If we got an error
if (snapshot.hasError) {
return Center(
child: Text(
'${snapshot.error} occured',
style: TextStyle(fontSize: 18),
),
);
// if we got our data
} else if (snapshot.hasData) {
// Extracting data from snapshot object
final List<Book> recommendedBooksML = snapshot.data;
return BookList(title, recommendedBooksML);
} else {
return SizedBox.shrink();
}
} else {
return Container();
}
}
// ... some code here
);
}
}
I navigate to a different screen Screen 2. And then back to Screen 1. I loose the future data and it starts Building again.
PS:I found a temporary workaround by storing the Future data in a Global Variable
List<Book> placeholder=[];
And then setting the value from future...placeholder=snapshot.data;
When Switching between Screen 1 and 2. I am checking
placeholder==[]?UserChoiceBooks (title):BookList(title,placeholder)
Is there a better way to keep data from snapshot so that switching between screen future value is not Lost?