I have a Maps of type
Map<String,Map<String,bool>> outerMap;
Map<String,bool> innerMap_1 ,innerMap_2;
I need to nest innerMaps inside outerMap.
innerMap_1 = { 'time_1':true , 'time_2':false };
innerMap_1 = { 'time_3':false ,'time_4':true };
outerMap = { 'date_1':innerMap_1 , 'date_2':innerMap2 };
I need to store outerMap as a string on the Sqlite Database. When I try
jsonEncode(outerMap);
There is an error because it is nested.
How to effectively convert the outerMap to String and then convert that string back to Map ?
outerMap = { 'date_1':innerMap_1 , 'date_2':innerMap2 };
The thing is that you had a spelling error and therefore there was an error. But in my solution I fixed that.
Another thing to notice is that in order to use the jsonEncode function you have to import the dart:convert package.
import 'dart:convert';
void main() {
Map<String, Map<String, bool>> outerMap;
Map<String, bool> innerMap_1, innerMap_2;
innerMap_1 = {'time_1': true, 'time_2': false};
innerMap_2 = {'time_3': false, 'time_4': true};
outerMap = {'date_1': innerMap_1, 'date_2': innerMap_2};
String json = jsonEncode(outerMap);
print(json);
print(jsonDecode(json));
}
You can test your dart code on dartpad.dev.
Related
I have string response like this, I got only below response of my api.
{authToken: msadnmsandnasdn}
and I have to convert as below.
{"authToken": "msadnmsandnasdn"}
So how i can do this please Help me.
You can use various manipulation operations to do that manually:
import 'dart:convert';
void main() {
var s = "{authToken: msadnmsandnasdn, name:risheek}";
var kv = s.substring(0,s.length-1).substring(1).split(",");
final Map<String, String> pairs = {};
for (int i=0; i < kv.length;i++){
var thisKV = kv[i].split(":");
pairs[thisKV[0]] =thisKV[1].trim();
}
var encoded = json.encode(pairs);
print(encoded);
}
Output:
{"authToken":"msadnmsandnasdn"," name":"risheek"}
You need to use jsonDecode on that string like this:
var response = {authToken: msadnmsandnasdn....};
var result = jsonDecode(response);
I'm searching for create a dynamic form which contain DropDownButtons.
Before do that, I'm trying something on DartPad to know if it's possible to call a list with some Strings.
Below an example about what I want to do (maybe what I'm searching for is now possible) :
void main() {
List<Map<String, String>> listOf3AInitial = [{"name": "4A"},
{"name": "5A"}
];
String _listOf = "listOf";
String _year = "3A";
String _type = "Initial";
var listOfType = "$_listOf$_year$_type";
print(listOfType);
}
In this case it print "listOf3AInitial" and I want to print the List {"name": "4A"},{"name": "5A"}.
How it is possible to do that ?
Regards
You have to map a string of it's value to do so. For example
List<Map<String, String>> listOf3AInitial = [{"name": "4A"}, {"name": "5A"}];
Map<String, List<Map<String, String>>> list3AInitialMap = {
"listOf3AInitial" : listOf3AInitial,
};
Now you can get a value from this map like
String _listOf = "listOf";
String _year = "3A";
String _type = "Initial";
var listOfType = "$_listOf$_year$_type";
print(list3AInitialMap[listOfType]);
Your var listOfType returns a String. Unfortunately, you cannot use/convert String as a variable name.
In this case, you may want to use a map:
void main() {
List<Map<String, String>> listOf3AInitial = [{"name": "4A"},{"name": "5A"}];
List<Map<String, String>> listOf3BInitial = [{"name": "4B"},{"name": "5B"}];
String _listOf = "listOf";
String _yearA = "3A"; //A
String _yearB = "3B"; //B
String _type = "Initial";
//Reference your lists in a map
Map<String, dynamic> myLists = {
"listOf3AInitial": listOf3AInitial,
"listOf3BInitial": listOf3BInitial
};
//This returns your listOf3AInitial
var listOfType = myLists["$_listOf$_yearA$_type"];
print(listOfType);
//You may also access it directly
print(myLists["$_listOf$_yearB$_type"]);
}
metas: "["<p>1</p>","<p>2</p>","<p>3/p>","<p>4</p>"]"
to
List<String> metas = ["<p>1</p>","<p>2</p>","<p>3/p>","<p>4</p>"]
I can use it in JS JSON.parse (meta), is there any way to do it in dart?
Use could use the jsonDecode function from dart:convert
import 'dart:convert';
void main() {
var x = '["<p>1</p>","<p>2</p>","<p>3/p>","<p>4</p>"]';
List metas = jsonDecode(x);
print(metas); // [<p>1</p>, <p>2</p>, <p>3/p>, <p>4</p>]
print(metas[0].runtimeType); // String
}
I am trying to make a request to a Hasura backend using Flutter, Chopper and Built Value and I am getting the following error
> When parsing the constructor GQLReq of type Hasura.GraphQL.Transport.HTTP.Protocol.GQLReq expected Object but got String.,
Chopper service
#ChopperApi(baseUrl: '/v1/graphql')
abstract class PostApiService extends ChopperService {
#Post()
Future<Response<BuiltPost>> get(#Body() String body);
static PostApiService create(AuthHeaderProvider authHeaderProvider) {
final client = ChopperClient(
baseUrl: 'https://arrivee-app-test.herokuapp.com',
services: [
_$PostApiService(),
],
converter: BuiltValueConverter(),
interceptors: [
HttpLoggingInterceptor(),
// HeadersInterceptor({'content-type': 'application/json'}),
HeadersInterceptor({'Authorization':'Bearer token'})
],
);
return _$PostApiService(client);
}
}
I make request with the following code
var request = RequestModel((b) => b
..query = fetchAccommodations()
..variables = null
..operationName = 'AccommodationGet');
var response = await client.get(request.toJson());
RequestModel
abstract class RequestModel
implements Built<RequestModel, RequestModelBuilder> {
String get query;
#nullable
String get variables;
String get operationName;
RequestModel._();
factory RequestModel([updates(RequestModelBuilder b)]) = _$RequestModel;
String toJson() {
return json
.encode(serializers.serializeWith(RequestModel.serializer, this));
}
static RequestModel fromJson(String jsonString) {
return serializers.deserializeWith(
RequestModel.serializer, json.decode(jsonString));
}
static Serializer<RequestModel> get serializer => _$requestModelSerializer;
}
Encountered the same error while trying to make a simple http POST call to Hasura in Angular Dart (no GraphQL client available).
I have found that the Json String had to be built in the following way :
String query = """
{
account {
id
}
}
""";
Map<String, dynamic> variables;
if (query.trimLeft().split(' ')[0] != 'query') {
query = 'query $docQuery';
}
var jsonMap = {'query': query, 'variables': variables};
final _headers = {'Content-Type': 'application/json'};
return _authHttpService.post(_apiUrl,
headers: _headers, body: json.encode(jsonMap));
Hope it helps anyone looking for a vanilla Dart solution.
I managed to solve it. posting here for future reference.
I let chopper do the conversion from a model to a string instead of doing it manually beforehand here
I changed the signature of the chopper service from :
#Post()
Future<Response<BuiltPost>> get(#Body() String body);
to
#Post()
Future<Response<BuiltPost>> get(#Body() RequestModel body);
and calling the service from:
var request = RequestModel((b) => b
..query = fetchAccommodations()
..variables = null
..operationName = 'AccommodationGet');
var response = await client.get(request.toJson());
to
var request = RequestModel((b) => b
..query = fetchAccommodations()
..variables = null
..operationName = 'AccommodationGet');
var value = await client.get(request);
Did several google searches, nothing helpful came up. Been banging my head against some errors when trying to do something that should be pretty simple. Convert a map such as {2019-07-26 15:08:42.889861: 150, 2019-07-27 10:26:28.909330: 182} into a list of objects with the format:
class Weight {
final DateTime date;
final double weight;
bool selected = false;
Weight(this.date, this.weight);
}
I've tried things like: List<Weight> weightData = weights.map((key, value) => Weight(key, value));
There's no toList() method for maps, apparently. So far I'm not loving maps in dart. Nomenclature is confusing between the object type map and the map function. Makes troubleshooting on the internet excruciating.
Following on Richard Heap's comment above, I would:
List<Weight> weightData =
mapData.entries.map( (entry) => Weight(entry.key, entry.value)).toList();
Don't forget to call toList, as Dart's map returns a kind of Iterable.
List<Weight> weightData = List();
weights.forEach((k,v) => weightData.add(Weight(k,v)));
Sometimes the typecast will fail and you can enforce it by doing:
List<Weight> weightData =
weightData.entries.map<Weight>( (entry) => Weight(entry.key, entry.value)).toList();
Example from my project where it wasn't working without typecast:
List<NetworkOption> networkOptions = response.data['data']['networks']
.map<NetworkOption>((x) => NetworkOption.fromJson(x))
.toList();
Use the entries property on the map object
This returns a List of type MapEntry<key,value>.
myMap.entries.map((entry) => "${entry.key} + ${entry.value}").toList();
You can also use a for collection to achieve the same.
var list = [for (var e in map.entries) FooClass(e.key, e.value)];
Details
Flutter 1.26.0-18.0.pre.106
Solution
/libs/extensions/map.dart
extension ListFromMap<Key, Element> on Map<Key, Element> {
List<T> toList<T>(
T Function(MapEntry<Key, Element> entry) getElement) =>
entries.map(getElement).toList();
}
Usage
import 'package:myApp/libs/extensions/map.dart';
final map = {'a': 1, 'b': 2};
print(map.toList((e) => e.value));
print(map.toList((e) => e.key));
You can do this:
List<Weight> weightData = (weights as List ?? []).map((key, value) => Weight(key,value)).toList()
or you can try:
List<Weight> weightData = List.from(weights.map((key, value) => Weight(key, value)))
If you need to convert Map values to a list, the simplest oneline code looks like this:
final list = map.values.toList();
Vidor answer is correct .any way this worked for me
List<String> list = new List();
userDetails.forEach((k, v) => list.add(userDetails[k].toString()));
its very simple just initialize a list of your custom object like this
List<CustomObject> list=[];
for (int i = 0; i < map.length; i++) {
CustomObject customObject= CustomObject(
date:map[i]['key'],
weight:map[i]['key']
);
list.add(CustomObject);
}
hope it works for you thanks
You simply don't need to. the values property is an Iterable<> of your objects. You can iterate over this or you can convert it to a list. For example,
// ignore_for_file: avoid_print
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets("convert Map to List of Objects", (tester) async {
final weight1 = Weight(const ValueKey("1"), DateTime.now(), 1);
final weight2 = Weight(const ValueKey("2"), DateTime.now(), 2);
final map = {weight1.key: weight1, weight2.key: weight2};
//You don't have to convert this to a list
//But you can if you want to
final list = map.values.toList();
list.forEach((w) => print("Key: ${w.key} Weight: ${w.weight} "));
});
}
class Weight {
final Key key;
final DateTime date;
final double weight;
bool selected = false;
Weight(this.key, this.date, this.weight);
}
Object Class
class ExampleObject {
String variable1;
String variable2;
ExampleObject({
required this.variable1,
required this.variable2,
});
Map<String, dynamic> toMap() {
return {
'variable1': this.variable1,
'variable2': this.variable2,
};
}
factory ExampleObject.fromMap(Map<String, dynamic> map) {
return ExampleObject(
variable1: map['variable1'] as String,
variable2: map['variable2'] as String,
);
}
}
Convert Map to Object List
List<ExampleObject> objectList = List<ExampleObject>.from(mapDataList.map((x) => ExampleObject.fromMap(x)));