Skip to content

Commit 6acb641

Browse files
committed
refactor: Improve message handling in Unity example by parsing JSON data
This commit enhances the message handling logic in the Unity example by parsing incoming messages as JSON. It updates the method checks to use parsed data, improving robustness and error handling. The changes ensure that speed and state updates are processed correctly, providing a more reliable interaction between Flutter and Unity.
1 parent 226e478 commit 6acb641

1 file changed

Lines changed: 23 additions & 12 deletions

File tree

example/lib/main.dart

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -537,34 +537,45 @@ class _UnityExampleScreenState extends State<UnityExampleScreen> {
537537
}
538538

539539
void _onMessage(GameMessage message) {
540-
_log('Message received: ${message.method}');
540+
_log('Message received: ${message.data}');
541541

542-
if (message.method == 'onReady') {
542+
// Parse the message data
543+
final json = message.asJson();
544+
if (json == null) return;
545+
546+
final method = json['method'] as String?;
547+
if (method == null) return;
548+
549+
_log('Method: $method');
550+
551+
if (method == 'onReady') {
543552
setState(() {
544553
_isReady = true;
545554
_lastMessage = 'Unity cube demo ready!';
546555
_direction = '← FROM UNITY';
547556
});
548-
} else if (message.method == 'onSpeedChanged') {
557+
} else if (method == 'onSpeedChanged') {
549558
try {
550-
final data = message.data as Map<String, dynamic>;
551-
setState(() {
552-
_currentSpeed = (data['speed'] as num).toDouble();
553-
_currentRpm = (data['rpm'] as num).toDouble();
554-
_lastMessage = 'Speed updated';
555-
_direction = '← FROM UNITY';
556-
});
559+
final data = json['data'] as Map<String, dynamic>?;
560+
if (data != null) {
561+
setState(() {
562+
_currentSpeed = (data['speed'] as num?)?.toDouble() ?? 0;
563+
_currentRpm = (data['rpm'] as num?)?.toDouble() ?? 0;
564+
_lastMessage = 'Speed updated';
565+
_direction = '← FROM UNITY';
566+
});
567+
}
557568
} catch (e) {
558569
_log('Error parsing speed data: $e');
559570
}
560-
} else if (message.method == 'onReset') {
571+
} else if (method == 'onReset') {
561572
setState(() {
562573
_rotationSpeed = 50;
563574
_rotationAxis = 'Y';
564575
_lastMessage = 'Cube reset';
565576
_direction = '← FROM UNITY';
566577
});
567-
} else if (message.method == 'onState') {
578+
} else if (method == 'onState') {
568579
setState(() {
569580
_lastMessage = 'State received';
570581
_direction = '← FROM UNITY';

0 commit comments

Comments
 (0)