Answer the question
In order to leave comments, you need to log in
Flutter State Management - Provider, how to avoid mistakes?
Due to little experience, I encountered an architectural error in the development of the application, namely the storage of the global session state of the application (for example, authorization data, user session settings, content filters). That is, I need something like $_SESSION in PHP.
There are several well-known solutions:
1. Declare a global variable outside the main function, write incoming data from the server into it, and pull it from any part of the code where you need to use initState and setState. As far as I know - this approach is not welcomed and not desirable.
2. The same as 1, but declare a variable inside the main function, and then pass it as an argument to each widget class. Not sure how reasonable this is.
3. Use Provider. However, there is an inconvenience. You can use the Provider only in the context of a widget, and change the values of the Provider class variables only after the widget is built ( Eg: via onPressed, onChange ) .
The Http request is executed before the widget is built, and it is not clear how to write the request data to the Provider class.
Please share your experience in solving the application states problem in Flutter
Here is my wrong login page example:
class PageStart extends StatefulWidget{
@override
State<StatefulWidget> createState() {
return _PageStartState();
}
}
//
class _PageStartState extends State<PageStart>{
var actinAuthProfile = ActionAuthProfile(); // for http query method
var status_page = 'load'; // status load page
var data = {}; // session authorization data
@override
void initState() {
super.initState();
actinAuthProfile.CheckAuth().then((gsDataProfile) { // http query - get session data
setState(() {
data = gsDataProfile; // data for Provider class
status_page = gsDataProfile['status']; // change status load page
});
});
}
//
@override
Widget build(BuildContext context) {
var authStateProfile = Provider.of<AuthStateProfile>(context);
authStateProfile.SetDataProfile(data); //! DON`T WORK !!!!!! Exception widget don`t build
switch ( status_page ) {
case 'no_connect':
return progressScreenWidget();
break;
case '/main': return PageMainr();
break;
default: return progressScreenWidget();
}
}
}
Answer the question
In order to leave comments, you need to log in
You need to write a function in the provider itself that makes a request to the server and saves the result in the provider, video .
To store the session on the device, you can use shared_preferences , but you need to pre-encrypt it, but not necessarily. Only root devices have access.
Or hive , encryption is already built in there.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question