How to convert list getting from future method to Map<String, dynamic> - list

I want to convert the list coming from getPosts method (getting result from the web json and stored in the posts list) to List
Post Class
class Post {
final int userId;
final String id;
final String title;
final String body;
Post(this.userId, this.id, this.title, this.body);
}
Future<List<Post>> getPosts() async {
var data = await http
.get("https://jsonplaceholder.typicode.com/posts");
var jasonData = json.decode(data.body);
List<Post> posts = [];
for (var i in jasonData) {
Post post = Post(i["userId"], i["id"], i["title"], i["body"]);
posts.add(post);
}
return posts;
}
I tried to put the result directly to this method
static List<Map> convertToMap({List myList }) {
List<Map> steps = [];
myList.forEach((var value) {
Map step = value.toMap();
steps.add(step);
});
return steps;
}
but it's not working, I see this error
The argument type 'List<Map<dynamic, dynamic>>' can't be assigned to the parameter type 'Map<String, dynamic>'.

Change List<Map> by List<Map<String, dynamic>>
static List<Map<String, dynamic>> convertToMap({List myList }) {
List<Map<String, dynamic>> steps = [];
myList.forEach((var value) {
Map step = value.toMap();
steps.add(step);
});
return steps;
}

Related

Error: A value of type 'List<String>' can't be assigned to a variable of type 'List<ChartData>', trying to create a Chart with a list of Strings,

I'm trying to create a graph and i don't know how to set values on this graph (I know how to set the values manually but i created a field in firestore that receives the value of x and y of the graph when you click on a button ), i'm using SyncFusion Flutter Chart (if you have any another idea to solve my problem feel free to say) and i'm trying to add the values ( String ) to the list and for that i Created in firestore when you click on the button (ChartData(x,y)) so all i need is add this string to the list of type ChartData, and for that i'm trying to use decode and split but now returned this error and i don't know how to solve. i'm sorry for the long text.
List<ChartData> convert(String input) {
List<ChartData> output;
try {
output = json.decode(input);
return output;
} catch (err) {
print('The input is not a string representation of a list');
return [ChartData(0, 0)];
}
}
List<ChartData> testim = testefinal.split(',');
final List<ChartData> list1 = convert(testefinal);
final List<ChartData> chartData = list1;
Error: A value of type 'List<String>' can't be assigned to a variable of type 'List<ChartData>'.
Full Code:
import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:mood3/telas/animacao.dart';
import 'package:ntp/ntp.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import '../model/GraphMood.dart';
class Graph extends StatefulWidget {
#override
State<Graph> createState() => _GraphState();
}
class _GraphState extends State<Graph> {
TooltipBehavior? _tooltipBehavior;
DateTime ntpTime = DateTime.now();
String testefinal = '';
_loadNTPTime() async {
FirebaseAuth auth = FirebaseAuth.instance;
FirebaseFirestore db = FirebaseFirestore.instance;
setState(() async {
ntpTime = await NTP.now();
});
}
Future _recuperarNome() async {
FirebaseAuth auth2 = FirebaseAuth.instance;
User? user = auth2.currentUser;
DocumentSnapshot ds = await db.collection('usuarios')
.doc(user!.uid)
.get();
Map<String, dynamic> dss = ds.data() as Map<String, dynamic>;
setState((){
testefinal = dss["moodGraph"];
});
print(testefinal);
}
FirebaseFirestore db = FirebaseFirestore.instance;
#override
initState(){
_recuperarNome();
_tooltipBehavior = TooltipBehavior(enable: true);
super.initState();
_loadNTPTime();
}
#override
Widget build(BuildContext context) {
List<ChartData> convert(String input) {
List<ChartData> output;
try {
output = json.decode(input);
return output;
} catch (err) {
print('The input is not a string representation of a list');
return [ChartData(0, 0)];
}
}
List<ChartData> testim = testefinal.split(',');
final List<ChartData> list1 = convert(testefinal);
final List<ChartData> chartData = list1;
return Scaffold(
body: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: CategoryAxis(),
// Chart title
title: ChartTitle(text: 'Mood Chart'),
// Enable legend
legend: Legend(isVisible: true),
// Enable tooltip
tooltipBehavior: _tooltipBehavior,
series: <ChartSeries>[
// Renders line chart
LineSeries<ChartData, int>(
dataSource: chartData,
xValueMapper: (ChartData data, _) => data.x.toInt(),
yValueMapper: (ChartData data, _) => data.y
)
]
)
)
)
);
}
}
class ChartData {
ChartData(this.x, this.y);
final double x;
final double y;
}
I think, output = json.decode(input) as List();

How to convert or equalize Query<Map<String, dynamic>> to List

I have BrandList in my Firebase like this;
How can I convert or equalize this Firebase List to List.
I tried this;
var brandsRef = _firestore.collection("vehicles1").where("Brands");
List brandsList = brandsRef;
But I got this error "A value of type 'Query<Map<String, dynamic>>' can't be assigned to a variable of type 'List'."
You need to use the document Id to get the query and then you can get the data which returns a Map.
From that Map, you can supply the key to retrieve the value. In this case, the key is "Brands".
var brandsQuery = await _firestore.collection("vehicles1").doc(document Id).get();
List brandList = brandsQuery.data()["Brands"];
First I would suggest to create a model of your class Brand in addition to the jsonSerialization classics:
class Brands {
Brands({this.brandName});
List<String> brandName;
Map<String, dynamic> toMap() {
return {
'Brands': brandName,
};
}
factory Brands.fromMap(Map<String, dynamic> map) {
return Brands(
brandName: List<String>.from(map['Brands']),
);
}
String toJson() => json.encode(toMap());
factory Brands.fromJson(String source) => Brands.fromMap(json.decode(source));
}
Then you need to add a few steps to the way you retreive elements:
var response = _firestore.collection("vehicles1").where("Brands").get();
final results =
List<Map<String, dynamic>>.from(response.docs.map((e) => e.data()));
Brands brands =
results.map((e) => Brands.fromMap(e)).toList();

Flutter : how save list of dynamic to shared preference

I am trying to save a list of data to shared preference and read these articles but don't works with me :
Flutter save List with shared preferences
Shared Preferences in Flutter cannot save and read List
I have this list :
var list =[
{
"id" : 1,
"name" : "ali"
},
{
"id" : 2,
"name" : "jhon"
}
];
I tried this :
setList() async {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
final SharedPreferences prefs = await _prefs;
prefs.setStringList('list', list);
}
I get this error : The argument type 'List<Map<String, Object>>' can't be assigned to the parameter type 'List<String>'
The error occurs because your list is of type Map<String, Object> and not a String. To fix this you can use jsonEncode method which converts it into a String
Future<void> setList() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final List<String> jsonList = list.map((item) => jsonEncode(item)).toList();
prefs.setStringList('list', jsonList);
}
If you now want to retrieve this list you have to use jsonDecode to convert it back to a Map<String, Object>.
List<Map<String, Object>> getList() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final List<String> jsonList = prefs.getStringList('list')
final List<Map<String, Object> list = jsonList.map((item) => jsonDecode(item)).toList();
return list;
}

Search and find the string in List of DTO class in flutter?

I have this DTO class and in response of API i get the list of this :
class ProjectCode {
String id;
String projectCode;
String projectTitle;
ProjectCode({this.id, this.projectCode, this.projectTitle});
ProjectCode.fromJson(Map<String, dynamic> json) {
id = json['Id'];
projectCode = json['ProjectCode'];
projectTitle = json['ProjectTitle'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['Id'] = this.id;
data['ProjectCode'] = this.projectCode;
data['ProjectTitle'] = this.projectTitle;
return data;
}
}
now how can i search in list and find the ProjectTitle that i need to find it and that method return the id in DTO ?
This is simple, you can use this method to find the String that you need to find. make method like this for everything do you need to search like this :
String find(List<ProjectCode> projectCodeList, String projectTitle) {
return projectCodeList
.firstWhere(
(projectCode) => projectCode.projectTitle.contains(projectTitle))
.id;
}

Flutter - Fill future list from json

I want to fill a list from json.
Future<List<Titles>> fetchTitle() async {
String url = "https://jsonplaceholder.typicode.com/posts";
final response = await http.get(url,headers: {'Content-Type': 'application/json'});
return titlesFromJson(utf8.decode(response.bodyBytes));
How to fill below list using fetchTitle method. I want to add "title" item from json.
final List myLists = [];
Expanded(
child: GridView.count(
crossAxisCount: 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
childAspectRatio: 1,
padding: EdgeInsets.only(left: 20, top: 20, right: 20),
children:List.generate(myLists.length, (index) {
return InkWell(
From the official documentation this is the way on how to fetch data from json and convert the response to list of model:
1- create a model for the post
class Post {
int userId;
int id;
String title;
String body;
Post({this.userId, this.id, this.title, this.body});
Post.fromJson(Map<String, dynamic> json) {
userId = json['userId'];
id = json['id'];
title = json['title'];
body = json['body'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['userId'] = this.userId;
data['id'] = this.id;
data['title'] = this.title;
data['body'] = this.body;
return data;
}
}
2 - import http package and fetch post from the link https://jsonplaceholder.typicode.com/posts
import 'package:http/http.dart' as http;
Future<List<Post>> fetchPosts(http.Client client) async {
final response = await client
.get('https://jsonplaceholder.typicode.com/posts');
return parsePosts(response.body);
}
3 - Use the method that you define on your model to create a list that contain posts
import 'dart:convert';
List<Post> parsePosts(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Post>((json) => Post.fromJson(json)).toList();
}
4 - to make a test that your code work, create a simple async main method that call fetchPosts with the await prefix because fetchPosts return a Future so if you don't use await you will get a future and not the List
void main() async {
List posts = await fetchPosts(http.Client());
// this will print the id and the title of posts
posts.forEach((post) => print('Post id: ${post.id} | Post title: ${post.title}'));
}
I hope this help!
To add the JSON result to a list, you may need to wait for the response and add it to the List. Since fetchTitle() method returns Future<List<Titles>>, when you await for it, you will get a List<Titles> which can be assigned to your myList.
myList = await fetchTitle();
Since we are using await, we may need to mark the method using async keyword.
void main() async {
List myList = [];
myList = await fetchTitle();
print(myList);
}