Home > other >  Payload data as a String, Flutter
Payload data as a String, Flutter

Time:02-02

I receive an object from my payload data (which has to be a String) like this: {id: 24VQUCeGD4KnW6tvfhj8MJjuASk, event: user}. Since it is a string now, how can I access the key and value pair of both items in flutter from a String? I have tried creating a model class for it, making a Map again out of the String, decoding it back to json object but all failed. How can I get the key/value pair in a proper way?

Code:

await _notificationsPlugin.show(
        id,
        'New notification',
        'You have received a new notification!',
        notificationDetails,
        payload: message.data.toString(), // the payload data has to be a string
      );

When you press on the notification:

onSelectNotification: (String data) async {
      //here is where I want to access the key/value pair of that String 'data'
// i tried something like this but failed

var someData = jsonEncode(jsonDecode(data));
var className = ClassName.fromJson(someData);
print(className.id);
.. but nothing prints

//...  some logic
}

class ClassName {
  ClassName({
    this.id,
    this.event,
  });

  String id;
  String event;

  ClassName.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    user = json['event'];
  }
}

Any form of help is appreciated!

CodePudding user response:

try this:

import 'dart:convert';

void processData(String data) {
  Map<String, dynamic> someData = jsonDecode(data);
  var className = ClassName.fromJson(someData);
  print(className.id);
}

class ClassName {
  ClassName({
    required this.id,
    required this.user,
  });

  String id;
  String user;

  ClassName.fromJson(Map<String, dynamic> json) :
    id = json['id'],
    user = json['user'];
 
}


void main() {
  processData("{\"id\": \"24VQUCeGD4KnW6tvfhj8MJjuASk\", \"user\": \"user\"}");
}

p.s it seems that your provided JSON has id and event keys but in your ClassName, you are reading id and user keys which doesn't exist.

CodePudding user response:

it happens that the id string isn't delimited so, you may try to custom decode like:

Map<String, String> decodePayload(String eventData) {
    final aString = eventData.substring(5, eventData.length - 1);
  
  
  final parts = aString.split(', ');
  final id = parts[0];
  final event = parts[1].substring(7, );
  return {'id': id, 'event':event};

}

It doesn't looks nice but it may works

  •  Tags:  
  • Related