I wanted to convert a string to map.
String value = "{first_name : fname,last_name : lname,gender : male, location : { state : state, country : country, place : place} }"
into
Map = { first_name : fname, last_name : lname, gender : male, location = { state : state, country : country, place : place } }
How do I convert the string into a map<String, dynamic>
where the value consists of string, int, object, and boolean?
I wanted to save the string to a file and obtain the data from the file.
If it were valid JSON you could use var decoded = json. decode(yourString); var map = Map. fromIterable(decoded, key: (e) => e.
To write a string to a file, use the writeAsString method: import 'dart:io'; void main() async { final filename = 'file. txt'; var file = await File(filename).
Dart Map is an object that stores data in the form of a key-value pair. Each value is associated with its key, and it is used to access its corresponding value. Both keys and values can be any type. In Dart Map, each key must be unique, but the same value can occur multiple times.
That's not possible.
If you can change the string to valid JSON, you can use
import 'dart:convert'; ... Map valueMap = json.decode(value); // or Map valueMap = jsonDecode(value);
The string would need to look like
{"first_name" : "fname","last_name" : "lname","gender" : "male", "location" : { "state" : "state", "country" : "country", "place" : "place"} }
You would have to change the way you create the string.
I'm guessing you are creating the string using the yourMap.toString()
method. You should rather use json.encode(yourMap)
, which converts your map to valid JSON, which you can the parse with json.decode(yourString)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With