Best place to save data in Flutter - flutter

I am using Clean Architecture in Flutter with Getx as State Management.
I have a list that i am taking from backend and i am showing it in UI and user can do some changes to this list as well.
where is the best place to store the data that is taken from backend and show from and change data.
right now in this example
the data is stored in Getx Controller.is this approach correct?or there is a better way?
class Controller extends GetxController{
List<Data> lsData = [];
fetchApi()async{
lsData = await fetchApi();
update();
}
add(Data data){
lsData.add(data);
update();
}
postApi()async{
await post(lsData);
}
}

there are many ways to save data in flutter, if you want to save data local there is Hive(i like this), Share preference, SQlite,GetX Storage and more
if you want to save data online I recommend Firestore
Hope this can be helpful :)

Related

How to view all Flutter app cache files and objects?

Listview / PageView Widgets do cache data and I don't know where, as well as Image.network and another bunch of widgets do cache data.
I know that you may clear cache by these methods below :-
and the methods mentioned in this thread
How to clear app cache programmatically on Flutter
setState(() {
imageCache.clear();
imageCache.clearLiveImages();
PaintingBinding.instance.imageCache.clear();
});
But I'm not sure that I have deleted ALL cached data allover the app,
Are these enough to clear all cached data or there are more ?
and How can you list and view all the cached data that are misteriously hidden somewhere I don't know where !?
please excuse my ignorance
This would not be the answer as I still don't know how to list and read all the data
but I could gather number of functions that make up a good cocktail to cleanup my heavy app
Future<void> deleteAllCacheThereIsInThisHeavyLaggyAppThatSucksMemoryLikeABlackHole() async {
await Future.wait(<Future>[
getTemporaryDirectory().then((Directory directory) async {
await Directory(directory.path).delete(recursive: true);
}),
getApplicationDocumentsDirectory().then((Directory directory) async {
await Directory(directory.path).delete(recursive: true);
}),
DefaultCacheManager().emptyCache(),
]);
imageCache.clear();
imageCache.clearLiveImages();
PaintingBinding.instance.imageCache.clear();
}
notice that i used this package https://pub.dev/packages/flutter_cache_manager as well
Please feel free to add any method that deletes any hidden magical cached file that I do not know about
I prefer to call these methods multiple times rather than having my app too heavy to navigate

Saving Local Data for a list on Flutter

I have an app that plays a sound. There is a list of sounds and I show that to an listview. So user can click a listtile and plays a sound. And I added a "Favourite" section. And it works fine. But when user closes the app it goes away. I tried to use SharedPrefences but I couldnt manage to do it. Because I need to save the whole list and I dont know how.
When I close the app, all my 'favourite' list goes away.
I will just share all the codes for better understanding:
Main.dart
Favourite.dart
Here is the explaining with the pictures:
Since the list of saved songs is a list of Strings you can use setStringList() method from SharedPrefences. When you want to save the list, use:
final prefs = await SharedPreferences.getInstance();
await prefs.setStringList('savedSounds', savedSounds);
Then when the application starts you load the songs by using:
final prefs = await SharedPreferences.getInstance();
savedSounds = prefs.getStringList('savedSounds') ?? [];
Then you can use a for-loop to also get the saved indexes, although I would recommend you to try only using one list of the saved songs.
for(int i = 0; i < savedSounds.length; i++){
if(soundList[i] == savedSounds[i]){
savedIndex.add(i.toString());
}
}
You can use the SQFlite package to store your List items locally. Here is the package:
https://pub.dev/packages/sqflite

Navigating to another screen gets slower and slower each time i repeat click, go back, click, go back

I have a Navigator.push and MaterialPageRoute() to navigate to another screen. But navigation to other screens gets slower and slower becuase in my initState() i have a method which initializes the json data which i show each time i navigate to another screen. The json data is big and i only use one file with big json data which has objects and each object is shown i different screens. In my usecase i have to use one file with big json data.
In my initState() i initialize the data i grabbed with the method setTestData() and inside this method i set the data inside an object:
late Map<String, dynamic> grabbedData = {};
setTestData() async {
await TestData()
.getTestData()
.then((result) => setState(() => grabbedData = result));
}
#override
initState() {
setTestData();
super.initState();
}
In my view i can for example navigate to another screen and then show different objects inside the same object json i grabbed in setTestData(). I only use one view called AppView() to show different screen so when i navigate for example from screen A to B, both A and B screen are shown with AppView() widget. This is necessary for my use case which is irrelevant for this question.
This is the navigation which i use to load another screen and which technacly runs initState() from AppView() again because the previous route is also AppView():
Navigator.push(
context,
MaterialPageRoute(
maintainState: false,
builder: (_) => AppView(
selectedMenuItems:
grabbedData['data']
['views'][
widget.selectedMenuItems[
index]
[
'content']],
)));
But the problem is that each time i navigate to AppView() and click back on my phone to show previous data from AppView() and navigate again, it re-initializes the state and so the proces is slowed after i repeat it a couple of times. How do i solve this problem?
Better to use Provider package for this task. Provider does not rebuild the widget rather it only updates the state of the widget so it is faster. Then, you can get your data or data stream only once at the beginning of your app or a particular screen. No need to generate data each time. Also, provider automatically disposes data when the screen is closed. It is recommended by flutter team as well and an awesome package. For more example, check some YouTube videos. For your particular problem, I think it is better to use provider.value. Check the references and hopefully later on you will understand what is a provider.value object.
If you are generating new data every time then you need to set your provider.value each time where you are using Navigator.push, otherwise if you do not use your provider at the beginning of your app at MaterialApp section then after the push the provider won't be available.
As an example, to add provider inside a push please follow the following code snippet:
Navigator.push(context,
MaterialPageRoute(builder: ((context) {
return StreamProvider<User>.value(
initialData: initialUserData,
value: userDataStream,
child: const UpdateUser(),
);
})));
Next, access the value in the UpdateUser page like this:
final user = Provider.of<User>(context);
If you are not using any data stream then just try the normal ChangeNotifierProvider and get the value from the Consumer. Try some youtube tutorials and you will love it.

How can you get the flutter visible page's state or context?

Sometimes an event (eg upload) starts async while the user is on one page. If they navigate away from that page the task's .then(...) will try to display the result on the page which is no longer visible, eg by means of a toast.
How can I get the context of the currently visible page at the time when the Future completes to display a snackbar, toast or dialog?
EDIT:
I see in the description of oktoast (https://pub.dev/packages/oktoast) that version 2 "Does not need the buildContext to be passed", and further
Quote:
Explain #
There are two reasons why you need to wrap MaterialApp
Because this ensures that toast can be displayed in front of all other
controls Context can be cached so that it can be invoked anywhere
without passing in context
This implies to me that there is a better way by providing a Material app ancestor somewhere....
For a simple Solution I would use the Provider Package. Keyword here is StateManagement (https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple)
The Model would look sth like this:
class UploadModel extends ChangeNotifier {
final bool loading = false;
void uploadXY() async{
loading = true;
// This call tells the widgets that are listening to this model to rebuild.
notifyListeners();
await realUploadStuff();
loading = true;
notifyListeners();
}
}
To start the upload:
Provider.of<UploadModel>(this).uploadXY()
To react if loading-bool changes:
if(Provider.of<UploadModel>(this).loading)...
You can find a simple Example here:
https://github.com/flutter/samples/blob/master/provider_counter/lib/main.dart

StreamBuilder and AsyncSnapshot + rxdart flutter question

I have final _fetcher = PublishSubject<MyModel>() ; in my bloc Component. Here is structure of MyModel:
MyModel { List<MyObjects> _objects = [];
List<MyObjects> get allObjects => _objects; }
also there is
Observable<MyModel> get myObjects => _fetcher.stream;
in bloc.
I have two pages, first displays list of MyObjects inside Listview.builder, and second displays selected MyObject data.
I'm trying to get data from myObjects using StreamBuilder.
In the first page all objects displays perfectly. But when I open a page with selected object, my AsyncSnapshot inside StreamBuilder always has connections.state waiting, although I have data in stream.
What am I doing wrong?
Having data doesn't mean you always have access to it.
By default streams (and subjects) don't store the data they received earlier. So if you're coming late to the party, then sorry for you but no data.
To solve this problem rxdart introduces a ReplaySubject and BehaviorSubject. Both are used so that late listeners can still grab the last few events. ReplaySubject will keep track of the N latest, while BehaviorSubject will keep only the last one.
Using a BehaviorSubject instead of PublishSubject should do the trick