SyncStateMixin
Syncing the state of a StatefulComponent from server to client.
Alongside with preloading some data on the server, you often want to also sync the data with the client.
The SyncStateMixin
lets you sync state of a StatefulComponent from the server with the client.
For a general guide about data-fetching on the server see Data Fetching.
Usage
The SyncStateMixin
accepts a second type argument for the data type that you want to sync. You then have to
implement the getState()
and updateState()
methods.
class MyState extends State<MyStatefulComponent> with SyncStateMixin<MyStatefulComponent, String> {
String myData = "Hello World";
// This will get the state to be sent to the client
// and is only executed on the server.
@override
String getState() {
return myData;
}
// This will receive the state on the client and is
// executed during [initState].
void updateState(String value) {
myData = value;
}
}
In order to send the data, it needs to be serialized on the server and deserialized on the client.
Therefore, the synced state must have a primitive serializable type, like String
, int
, double
, bool
or Map
s or List
s of these.
If you want to sync non-primitive values like custom data classes, you need to handle encoding and decoding
manually in the getState()
and updateState()
methods respectively.
Alternatives
-
Check out the @sync annotation for an even easier way to sync state of a
StatefulComponent
between server and client, including support for custom data types. -
Check out @client components, that support passing data from the server to the client as part of the component parameters, including support for custom data types.