Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting string to map in dart

Tags:

flutter

dart

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.

like image 509
Daniel Mana Avatar asked Apr 04 '18 12:04

Daniel Mana


People also ask

How do you parse a string to a Dart Map?

If it were valid JSON you could use var decoded = json. decode(yourString); var map = Map. fromIterable(decoded, key: (e) => e.

How do I convert a string to a Dart file?

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).

What is Map () in Dart?

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.


2 Answers

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"} } 
like image 174
Günter Zöchbauer Avatar answered Oct 24 '22 10:10

Günter Zöchbauer


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).

like image 32
leodriesch Avatar answered Oct 24 '22 10:10

leodriesch