https://pub.dev/packages/provider
I used this package for the cart and it works.
But when the app closes, the cart model becomes empty.
What can I do for this problem?
I want to save the previous data when the app is opened.
thanks
you can also use the offline database
for example SQFLITE
Using something like Shared_Prefs sould solve it
it will store your data locally and retrieve them in your providers
create instance
SharedPreferences prefs = await SharedPreferences.getInstance();
set your data
await prefs.setInt('counter', 1);
in your provider retrieve if exist like this
if(prefs.getInt('counter') != null){
someVar = prefs.getInt('counter');
}
you can remove like
prefs.remove('counter');
Note: you can save/retrieve with one of the following types
Only primitive types can be used: int, double, bool, string, and stringList.
Related
I made an API call and returned a list data and few other values. I made the API call in one screen in the initState now and I need the list and other data in other 2 screens without Navigation. Is this possible. I am also using provider package. I am new to flutter so any help would be highly appreciated. Thank You.
List<YourClassName> list = [];
class ExampleProvider with ChangeNotifier {
getList(){
list = await yourApiCall();
notifyListeners();
}
}
Your provider class should look like this. When your api returns, you need to use that equation. With that way you can call it everywhere your list with
Provider.of<ExampleProvider>(context).list;
I'm working on flutter app that uses php apis for server and sqlite for local data.
The problem is with "compute()".
Here is the explanation :
I have three functions that receives data from api on the server, then add the data to my local database (sqlite) table.
First function to get data from server.
Future<List<Map<String, dynamic>>> getServerData(int vers)async {
//my code
}
Second function to insert data into local database:
Future<int> addNewData(List<Map<String, dynamic>>)async {
//my code
}
Third function to call the first and second function:
Future<bool> checkServerData(int vers)async {
List<Map<String, dynamic>> sdt= await getServerData(vers);
int res=await addNewData(sdt);
if(res>0) return true;
else return false;
}
I want to call the third function in a compute function:
compute(checkServerData, 2);
When did that I found this error:
null check operator used on null value.
Note*:
If I used it without calling local database it works good.
The error appears if I called the database to insert data into.
When I searched about this issue I found that it's not allowed to access any resources which generated in one thread from another thread. But I didn't understand exactly how to resolve it or how to use another way that do the same idea.
After searching about the issue specified, I found those workaround solutions:
1: if the process is very important to work in background, you can use the Isolate package classes and functions which allow all isolated processes or contexts to share data between them as messages sending and receiving. But it's something complex for beginners in flutter and dart to understand these things, except those who know about threading in another environments.
To now more about that I will list here some links:
Those for flutter and pub documentation:
https://api.flutter.dev/flutter/dart-isolate/dart-isolate-library.html
https://api.flutter.dev/flutter/dart-isolate/Isolate-class.html
https://pub.dev/packages/flutter_isolate
This is an example in medium.com website:
https://medium.com/flutter-community/thread-and-isolate-with-flutter-30b9631137f3
2: the second solution if the process isn't important to work on background:
using the traditional approaches such as Future.builder or async/await.
You can know more about them here:
https://www.woolha.com/tutorials/flutter-using-futurebuilder-widget-examples
https://dart.dev/codelabs/async-await
and you can review this question and answers in When should I use a FutureBuilder?
I have a class for Player that has nextDate, loginDate and saveDate.
Below code works fine and able to retrieve the fields.
DocumentSnapshot documentSnapshot =
await db.collection(Paths.playersPath).doc(uid).get();
Player player = Player.fromFirestore(documentSnapshot);
print('print ${player.nextDate}');
print('print ${player.loginDate}');
print('print ${player.saveDate}');
My question now is if it is possible to use a variable for the nextDate, loginDate and saveDate so that I can just pass which date should I retrieve.
I tried the following but it is not working.
String dateName = 'nextDate';
DocumentSnapshot documentSnapshot =
await db.collection(Paths.playersPath).doc(uid).get();
Player player = Player.fromFirestore(documentSnapshot);
print('print ${player.$dateName}');
Please help. Thanks!
As far as the code snippet is concerned, I can see you have already defined a method fromFirebase to serialize it, in that case you must extract the data payload from the DocumentSnapshot provided by the Firebase DB by using the data method provided by the DocumentSnapshot class. The problem in your case is you're trying to serialize the DocumentSnapshot itself which is not a class of type Map<String, dynamic> which is need for json serialization. If you take a look at the docs, the data method provides a Map<String, dynamic>
Another alternative could be
If you are using FlutterFire plugins that are officially developed by the Firebase and Flutter teams, you can use the withConverter method which can serialize the response for you to the Player class in your case. Here you can find more info about the same.
unluckily, in Flutter mirrors are not available.
You can look it up in the official documentation about this matter.
Nonetheless, the most straightforward workaround is using a Map, so that the keys in that map are your options, and the values the actual property you want to use.
There's a good example in this previous answer.
How could you store something like that even when the app is closed in Flutter:
Class myList {
String id;
List<Item> list;
}
Class Item{
//Many property’s
}
I thought maybe I could do that with "sqflite", a flutter dependency, but I have no Idea how I could store there this List<Item>. Do you have any idea?
Btw: I need multiple of these "myList" instances.
You can store it using sqflite,hive or shared preferences.Try to save it under flutter shared preferences. These are two methods that you can use.
Using shared preferences
1)First create a shared preference instance
SharedPreferences prefs = await SharedPreferences.getInstance();
Then save the relevant data type.here you need to put a object list so add the list and convert it to the String using jsonEncode.
Map<String,List<Item>> map={mylist.id: mylist.list};
prefs.setString("itemList", json.encode(map));
Then you can retrieve data like this
Map<String,List<Item>> map=json.decode(prefs.getString("itemList")).asMap();
2)Using Hive
First Create the hive databse.you can put any name here
var box = Hive.box('myBox');
Then add the object in to that database
var myList = myList()
..id = your id here
..list = add list here;
var name = box.add(myList);
You can get anywhere this data list.
print(box.getAt(0));
You can try hive package. It is a lightweight local storage passage and it is a good idea to use hive because it has better benchmarks for reading and writes. You can search for the tutorial for the hive. or just read the documentation.
I created an project using Provide. After, for saving changes on my app, I tried to use shared_preferences plugin. But I cant't use it...!
How can I do..?
You can write like this:
sharedPrefs = await SharedPreferences.getInstance();
sharedPrefs.setString('youVariableName', Provider.of<YourModel>(context, listen: false).youVariableName);
of course write this when you have value in Provider variable.