[Flutter/Dart] Initialize state with remote database data in redux
Things to do
Use Redux for state management. Let the state be AppState.
Start acquiring data from remote database when app starts
Get Data
Waiting indicator is displayed during acquisition
Create AppState from acquired data
Draw UI based on created AppState
Methods
To achieve 3, 4, and 5, add a "fetched" flag to AppState (*1).
The view switches the display based on this flag (*2).
If you add the flag as an AppState variable, the view will automatically be rebuilt when the flag changes.
For 1, let's add an Action (FetchDataAction) that handles data acquisition
Start fetching data from the remote database by dispatching a FetchDataAction.
In the middleware, when FetchDataAction is dispatched, the data is acquired (above 2), and when completed, an action (ExchangeStateAction) is dispatched to replace the contents of the store with the acquired AppState (*3).
At this time, also change the value of the acquisition completion flag (*4).
When the ExchangeStateAction is dispatched, the reducer replaces the store state (*5).
The code looks like this:
class AppState{
final ItemListState itemListState;
final bool fetched; //(※1)
}
//middleware
void AppStateMiddleWare(Store<AppState> store, dynamic action, NextDispatcher next) async {
if (action is FetchDataAction){
if (!store.state.fetched) {
AppState state = await getData(); //data acquisition
state = state.changeFetched(true); //(※4)
store.dispatch(ExchangeStateAction(state)); //(※3)
}
}
//・・・
}
//reducer
AppState appStateReducer(AppState state, action){
if (action is ExchangeStateAction){
return action.state; //(※5)
}
//・・・
}
//view
@override
Widget build(BuildContext context) {
return StoreConnector<AppState, bool>(
converter: (store) => store.state.fetched,
builder: (context, fetched)=> Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => fetched? MainPage(context):
CircularProgressIndicator(); //(※2)
)
),
);
}
Lastly
It's easy to understand, but I had a hard time at first. In redux, it takes a little while to get used to where and what processing is done.
Recent Posts
See AllWhat want to do I want to create an input form using TextField. For example, if the input content is a monetary amount, I would like to...
What want to do There is a variable that remain unchanged once the initial value is determined. However, it cannot be determined yet when...
What want to do As the title suggests. Place two widgets in one line on the screen One in the center of the screen and the other on the...
コメント