Bug when trying to fetch data from node.js api to flutter - node.js

I have searched for a solution but couldn't find any, basically when I search for an account inside the app it shows up and looking fine but when I press it to get to the profile details screen it keeps loading and it seems to never get the data.
Below is the code for the response
import 'dart:convert';
ResponseUserSearch responseUserSearchFromJson(String str) => ResponseUserSearch.fromJson(json.decode(str));
String responseUserSearchToJson(ResponseUserSearch data) => json.encode(data.toJson());
class ResponseUserSearch {
ResponseUserSearch({
required this.resp,
required this.message,
required this.anotherUser,
required this.analytics,
required this.postsUser,
required this.isFriend,
required this.isPendingFollowers
});
bool resp;
String message;
AnotherUser anotherUser;
Analytics analytics;
List<PostsUser> postsUser;
int isFriend;
int isPendingFollowers;
factory ResponseUserSearch.fromJson(Map<String, dynamic> json) => ResponseUserSearch(
resp: json["resp"],
message: json["message"],
anotherUser: AnotherUser.fromJson(json["anotherUser"]),
analytics: Analytics.fromJson(json["analytics"]),
postsUser: List<PostsUser>.from(json["postsUser"].map((x) => PostsUser.fromJson(x))),
isFriend: json["is_friend"],
isPendingFollowers: json["isPendingFollowers"]
);
Map<String, dynamic> toJson() => {
"resp": resp,
"message": message,
"anotherUser": anotherUser.toJson(),
"analytics": analytics.toJson(),
"postsUser": List<dynamic>.from(postsUser.map((x) => x.toJson())),
"is_friend": isFriend,
"isPendingFollowers": isPendingFollowers
};
}
class Analytics {
Analytics({
required this.posters,
required this.friends,
required this.followers,
});
int posters;
int friends;
int followers;
factory Analytics.fromJson(Map<String, dynamic> json) => Analytics(
posters: json["posters"],
friends: json["friends"],
followers: json["followers"],
);
Map<String, dynamic> toJson() => {
"posters": posters,
"friends": friends,
"followers": followers,
};
}
class AnotherUser {
AnotherUser({
required this.uid,
required this.fullname,
required this.phone,
required this.image,
required this.cover,
required this.birthdayDate,
required this.createdAt,
required this.username,
required this.description,
required this.isPrivate,
required this.email,
});
String uid;
String fullname;
String phone;
String image;
String cover;
dynamic birthdayDate;
DateTime createdAt;
String username;
String description;
int isPrivate;
String email;
factory AnotherUser.fromJson(Map<String, dynamic> json) => AnotherUser(
uid: json["uid"],
fullname: json["fullname"],
phone: json["phone"] ?? '',
image: json["image"] ?? '',
cover: json["cover"] ?? '',
birthdayDate: DateTime.parse(json["birthday_date"] ?? '2021-10-22T20:17:53'),
createdAt: DateTime.parse(json["created_at"] ?? '2021-10-22T20:17:53'),
username: json["username"],
description: json["description"] ?? '',
isPrivate: json["is_private"],
email: json["email"],
);
Map<String, dynamic> toJson() => {
"uid": uid,
"fullname": fullname,
"phone": phone,
"image": image,
"cover": cover,
"birthday_date": birthdayDate,
"created_at": createdAt.toIso8601String(),
"username": username,
"description": description,
"is_private": isPrivate,
"email": email,
};
}
class PostsUser {
PostsUser({
required this.postUid,
required this.isComment,
required this.typePrivacy,
required this.createdAt,
required this.images
});
String postUid;
int isComment;
String typePrivacy;
DateTime createdAt;
String images;
factory PostsUser.fromJson(Map<String, dynamic> json) => PostsUser(
postUid: json["post_uid"],
isComment: json["is_comment"],
typePrivacy: json["type_privacy"],
createdAt: DateTime.parse(json["created_at"]),
images: json["images"],
);
Map<String, dynamic> toJson() => {
"post_uid": postUid,
"is_comment": isComment,
"type_privacy": typePrivacy,
"created_at": createdAt.toIso8601String(),
"images": images,
};
}
below is the profile page where I call that data
class ProfileAnotherUserPage extends StatefulWidget {
final String idUser;
const ProfileAnotherUserPage({Key? key, required this.idUser}) : super(key: key);
#override
State<ProfileAnotherUserPage> createState() => _ProfileAnotherUserPageState();
}
class _ProfileAnotherUserPageState extends State<ProfileAnotherUserPage> {
#override
Widget build(BuildContext context) {
return BlocListener<UserBloc, UserState>(
listener: (context, state) {
if( state is LoadingFollowingUser ){
modalLoading(context, 'Duke u ngarkuar...');
}else if( state is FailureUserState ){
Navigator.pop(context);
errorMessageSnack(context, state.error);
}else if( state is SuccessFollowingUser ){
Navigator.pop(context);
setState(() {});
}
},
child: Scaffold(
backgroundColor: Colors.white,
body: SafeArea(
child: FutureBuilder<ResponseUserSearch>(
future: userService.getAnotherUserById(widget.idUser),
builder: (context, snapshot) {
return !snapshot.hasData
? const _LoadingDataUser()
: _BodyUser(responseUserSearch: snapshot.data!);
},
),
),
),
);
}
}
class _BodyUser extends StatelessWidget {
final ResponseUserSearch responseUserSearch;
const _BodyUser({ Key? key, required this.responseUserSearch }) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView(
physics: const BouncingScrollPhysics(),
children: [
_CoverAndProfile(user: responseUserSearch.anotherUser),
const SizedBox(height: 10.0),
_UsernameAndDescription(user: responseUserSearch.anotherUser),
const SizedBox(height: 30.0),
_PostAndFollowingAndFollowers(analytics: responseUserSearch.analytics),
const SizedBox(height: 30.0),
_BtnFollowAndMessage(
isFriend: responseUserSearch.isFriend,
uidUser: responseUserSearch.anotherUser.uid,
isPendingFollowers: responseUserSearch.isPendingFollowers,
username: responseUserSearch.anotherUser.username,
avatar: responseUserSearch.anotherUser.image,
),
const SizedBox(height: 20.0),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
height: 46,
child: Column(
children: [
const Icon(Icons.grid_on_rounded, size: 30),
const SizedBox(height: 5.0),
Container(
height: 1,
color: Colors.grey[300],
)
],
),
),
const SizedBox(height: 5.0),
_ListFotosAnotherProfile(
posts: responseUserSearch.postsUser,
isPrivate: responseUserSearch.anotherUser.isPrivate,
isFriend: responseUserSearch.isFriend,
),
],
);
}
}
below is the backend code for this particular problem
export const getAnotherUserById = async (req: Request, res: Response): Promise<Response> => {
try {
const conn = await connect();
const [ userdb ] = await conn.query<RowDataPacket[]>(`CALL SP_GET_USER_BY_ID(?);`, [ req.params.idUser ]);
const posters = await conn.query<RowDataPacket[]>(' SELECT COUNT(person_uid) AS posters FROM posts WHERE person_uid = ?', [req.params.idUser]);
const friends = await conn.query<RowDataPacket[]>('SELECT COUNT(person_uid) AS friends FROM friends WHERE person_uid = ?', [req.params.idUser]);
const followers = await conn.query<RowDataPacket[]>('SELECT COUNT(person_uid) AS followers FROM followers WHERE person_uid = ?', [req.params.idUser]);
const posts = await conn.query<RowDataPacket[]>(`CALL SP_GET_POST_BY_IDPERSON(?);`, [req.params.idUser]);
const isFollowing = await conn.query<RowDataPacket[]>('CALL SP_IS_FRIEND(?,?);', [req.idPerson, req.params.idUser]);
const isPendingFollowers = await conn.query<RowDataPacket[]>(`CALL SP_IS_PENDING_FOLLOWER(?,?)`, [ req.params.idUser, req.idPerson ]);
conn.end();
return res.json({
resp: true,
message: 'Get Another User by id',
anotherUser: userdb[0][0],
analytics: {
'posters' : posters[0][0].posters,
'friends' : friends[0][0].friends,
'followers': followers[0][0].followers
},
postsUser: posts[0][0],
is_friend: isFollowing[0][0][0].is_friend,
isPendingFollowers: isPendingFollowers[0][0][0].is_pending_follower
});
} catch(err) {
return res.status(500).json({
resp: false,
message: err
});
}
}
This is the getAnotherUserById function
Future<ResponseUserSearch> getAnotherUserById(String idUser) async {
final token = await secureStorage.readToken();
final resp = await http.get(Uri.parse('${URLS.urlApi}/user/get-another-user-by-id/'+ idUser),
headers: { 'Accept': 'application/json', 'xxx-token': token! }
);
return ResponseUserSearch.fromJson(jsonDecode(resp.body));
}

Related

Display JSON data in Flutter

I want to display some data I am receiving from an API, this is the data I am receiving from my Node JS server:
[
{
"NAME": "Matematicas"
},
{
"NAME": "Naturales"
},
{
"NAME": "Ciencias Sociales"
},
{
"NAME": "Lenguaje"
},
{
"NAME": "Religion"
}
]
This is how I am receiving the data in my front end (UPDATED WITH #Mofidul Islam):
Future<List<Subject>> fetchSubject() async {
var url = Uri.http('localhost:8000', "/subjects");
var prefs = await SharedPreferences.getInstance();
var token = prefs.getString('token');
final response = await http.get(
Uri.parse('http://localhost:8000/subjects'),
headers: {'x-access-token': token!});
print(response.body);
List<dynamic> list = "[" + response.body + "]" as List<dynamic>;
List<Subject> subjectList = [];
list.forEach((element) {
subjectList.add(Subject.fromJson(element));
});
return subjectList;
}
This is the class to handle the incoming data (UPDATED WITH #Mofidul Islam):
class Subject {
final String name;
Subject({
required this.name,
});
factory Subject.fromJson(Map<String, dynamic> json) {
return Subject(name: json['NAME'] as String);
}
parseJson(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Subject>((json) => Subject.fromJson(json)).toList();
}
}
This is my init state:
void initState() {
super.initState();
futureSubject = fetchSubject();
}
This is how I am trying to display the data:
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Materias',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Materias'),
),
body: Center(
child: FutureBuilder<List<Subject>>(
future: futureSubject,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
children: snapshot.data!
.map((subject) => Text(subject.name))
.toList(),
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
),
),
),
);
}
However, the only thing being displayed when the page loads is:
Matematicas
I am trying to achieve 2 things:
Display the data in a list fashion like:
Subject Name
Matematicas
Naturales
Ciencias Sociales
Lenguaje Religion
Be able to use them as a link to another page when clicked
PD: If I remove the index access [0] on return Subject.fromJson(jsonDecode(response.body)[0]);
I get Expected a value of type Map<String, dynamic> but got one of type List<dynamic>
Any recommendations or guide on how to go through this?
Thank you for your time
You need to loop it
parseJson(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed
.map<Subject>((json) => Subject.fromJson(json))
.toList();
}
and change your api call to this
Future<List<Subject>> fetchSubject() async {
.....
return parseJson(json.encode(response.body));
}
sorry for my english.
Please try this one and return List from api method
Future<List<Subject>> fetchSubject() async {
var url = Uri.http('localhost:8000', "/subjects");
var prefs = await SharedPreferences.getInstance();
var token = prefs.getString('token');
final response = await http.get(Uri.parse('http://localhost:8000/subjects'),
headers: {'x-access-token': token!});
List<dynamic>list=response.body as List<dynamic>;
List<Subject>subjectList=[];
list.forEach((element){
subjectList.add(Subject.fromJson(element));
});
return subjectList;
}
refactor UI like this
Center(
child: FutureBuilder<List<Subject>>(
future: futureSubject,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(children: snapshot.data.map((subject)=>Text(subject.name)).toList(),);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
),
)

How to send a notification for a specific token, flutter, firebase messaging and node.js

I am designing an application and in it I will have a notification system between clients after an onCreate event.
Here is my index.js code
const functions= require("firebase-functions");
const admin =require("firebase-admin");
admin.initializeApp();
var fcm = admin.messaging();
// Node.js e.g via a Firebase Cloud Function
exports.sendPush = functions.firestore.document('notifications/{notificationId}').onCreate((change, context)=>{
const chauffeur = change.after.data().chauffeur;
const date_reception = change.after.data().date_reception;
const send_name = change.after.data().send_name;
const token = change.after.data().token;
console.log('chauffeur' + chauffeur);
console.log('date_reception' + date_reception);
console.log('send_name' + send_name);
console.log('token' + token);
const payload = {
notification:{
title: 'New message',
body: 'Message reçu de' + chauffeur,
sound: "default",
},
data:{
'chauffeur':chauffeur,
'date_reception': date_reception,
'send_name': send_name,
},
}
return admin.messaging().sendToDevice(token, payload);
});
et mon code dart&flutter
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
Future<void> _messageHandler(RemoteMessage message) async {
print('background message ${message.notification!.body}');
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(_messageHandler);
runApp(MessagingTutorial());
}
class MessagingTutorial extends StatelessWidget {
static const String idScreen = "note";
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Firebase Messaging',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Firebase Messaging'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, this.title}) : super(key: key);
final String? title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late FirebaseMessaging messaging;
String? notificationText;
#override
void initState() {
super.initState();
messaging = FirebaseMessaging.instance;
messaging.getToken().then((value) {
print(value);
});
FirebaseMessaging.onMessage.listen((RemoteMessage event) {
RemoteNotification? notification = event.notification;
AndroidNotification? androidNotification = event.notification!.android;
print("message recieved");
print(event.notification!.body);
print(event.data.values);
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Notification ${event.data['title']}"),
content: Text(event.notification!.body!),
actions: [
Row(children: [
TextButton(
child: Text("Annuler"),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
child: Text("Ok"),
onPressed: () {
Navigator.of(context).pop();
},
)
])
],
);
});
});
FirebaseMessaging.onMessageOpenedApp.listen((message) {
print('Message clicked!');
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title!),
),
body: Center(child: Text("Messaging Tutorial")),
);
}
}
The problem is, when I save in my "notifications" collection, the notification doesn't show even in the background, not even in forground.
After saving in the collection, the number of uses of the function increases but no effect in the application.
usage for the function
When I send the test message from firebase cloud messaging, everything is working fine
Cloud messaging test
I don't know how to fix this, if anyone can help me i would be very happy.
Thank you
There could be a lot of points that fail here. The cold start could cause that you don't wait enought for the notification. When your App is open it won't show anything if you havend written code for it to handle messages while in focus. You could have an outdated notification token. Do you update it on your database?
Can you try it with this shema of the payload to:
const payload = {
notification: {
title: "title",
body: "body",
},
webpush: {
notification: {
title: "title",
body: "body",
},
},
data: {
test: 'test',
},
}

How to update the values using NodeJS API

I created a user profile screen, where user can also edit the fields by clicking on edit button, it will appear a popup dialogue where i display the fields which are allowed to edit. And I am using API which i create it using NodeJS to update that fields, it is working, values are updating.
Problem:
There are 5 fields in edit dialogue box (email, phoneNo, address, education and martialstatus), but if user only want to edit the education field, and want rest field remain same, and when user click on update change button where i call the api, it only update the that field which is edited and update the other field to null, because it gets null value from the field controller (i am passing the textfield controller to api body parameter).
Solution which i think:
It can be done using conditions (if-else) to handle the null value, by passing the old values which i am getting using shared preference, but it will be not efficient, because there are 5 fields yet, but if in future if edit fields number increase, then more condition (checks) will be needed.
here is backend api code:
updateprofile = (req,res)=>{
jwt.verify(req.body.token, 'secret' , function(err, decoded) {
if(err) {
err["expiredAt"] = err["expiredAt"].toLocaleString();
res.status(300).json(err)
}
else
{
User.find({"username":req.body.username,_id: req.body.id},function(err,data){
console.log(req.body)
User.updateOne({"username":req.body.username, _id: req.body.id}, {"email":req.body.email,"education":req.body.education,"PhoneNo":req.body.PhoneNo,"address":req.body.address,"martialstatus":req.body.martialstatus},function(err,dat){
if(err)
res.json("You Last login Yesterday");
else
{
var token = jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: "30 minute"})
res.status(200).json({auth: true, AccessToken: token,email:req.body.email,education:req.body.education,phone:req.body.PhoneNo,address:req.body.address,martialstatus:req.body.martialstatus})
}
})})
}})}
here is edit dialogue and shared preference code:
String getname="";
String getemail="";
String getdesignation="";
String getType="";
String getId="";
String getToken="";
String getEducation="";
String getPhone="";
String getMartialStatus="";
String getAddress="";
String getDob="";
_userDetails() async{
SharedPreferences myPrefs=await SharedPreferences.getInstance();
setState(() {
getname=myPrefs.getString('name');
getemail=myPrefs.getString('email');
getdesignation=myPrefs.getString('designation');
getType=myPrefs.getString('type');
getId=myPrefs.getString('UserId');
getToken=myPrefs.getString('accesstoken');
getPhone=myPrefs.getString('phone');
getEducation=myPrefs.getString('education');
getMartialStatus=myPrefs.getString('martialstatus');
getAddress=myPrefs.get('address');
getDob=myPrefs.get('DOB');
});
}
_displayTextInputDialog(BuildContext context) {
return showDialog(
context: context,
builder: (context) {
return
Center(child:
Column(children: <Widget>[
AlertDialog(
title: Text('Profile Edit'),
content: Column(children: <Widget>[
TextField(
onChanged: (value) {
setState(() {
valueText = value;
});
},
controller: email,
decoration: InputDecoration(hintText: getemail,icon: Icon(Icons.email)),
),
TextField(
onChanged: (value) {
setState(() {
valueText = value;
});
},
controller: phone,
decoration: InputDecoration(hintText: getPhone,icon: Icon(Icons.phone)),
),
TextField(
onChanged: (value) {
setState(() {
valueText = value;
});
},
controller: address,
decoration: InputDecoration(hintText: getAddress,icon: Icon(Icons.location_on)),
),
TextField(
onChanged: (value) {
setState(() {
valueText = value;
});
},
controller: education,
decoration: InputDecoration(hintText: getEducation,icon: Icon(Icons.library_books)),
),
TextField(
onChanged: (value) {
setState(() {
valueText = value;
});
},
controller: martialstatus,
decoration: InputDecoration(hintText: getMartialStatus,icon: Icon(Icons.group)
),
)],),
actions: <Widget>[
FlatButton(
color: Colors.green,
textColor: Colors.white,
child: Text('Update Changes'),
onPressed: () {
setState(() {
valuebutton = valueText;
updateProfile(); //here calling the api function to udpate the values
Navigator.pop(context);
});
},
),
],)
],
));
});
}
here i'm using api and calling the function on update changes button
Dio dio = new Dio();
var data={};
Future updateProfile() async {
try{
var data={
"username":getname,
"id":getId,
"token":getToken,
"email":email.text,
"PhoneNo":phone.text,
"martialstatus":martialstatus.text,
"address":address.text,
"education":education.text
}; dio
.post(localHostUrlUpdateProfile, data: json.encode(data))
.then((onResponse) async {
showDialog(context: context,
builder: (BuildContext context){
return AdvanceCustomAlert(
title: "Profile Updated",
descriptions:"Profile is updated successfully!",icon: Icons.check,
bgcolor: Colors.green,
fgcolor: Colors.green,);
}
);
});}
catch (e) {
print("error");
bool checkStatus =
OSError.noErrorCode == 113 || OSError.noErrorCode == 101;
print(checkStatus);
print(OSError.noErrorCode == 113);
if (e is DioError) {
print(e.response);
}
if (checkStatus == false) {
print("con er");
showDialog(
context: context,
builder: (BuildContext context) {
return AdvanceCustomAlert(
title: "Connection Error",
descriptions: "An unknown network error occured.",
icon: Icons.error,
bgcolor: Colors.red,
fgcolor: Colors.red,
);
});
}
}
}
hope all clear, please help if anyone know how to do this.
i just reduced the condition logic to this
if(email.text==""){
email.text=getemail;
}
if(phone.text==""){
phone.text=getPhone;
}
education.text=getEducation;
}
if(address.text==""){
address.text=getAddress;
}
if(martialstatus.text==""){
martialstatus.text=getMartialStatus;
}
it is working, would appreciate if someone know the better solution than this.

LiveQuery does not work, if there is ParseConnectivityProvider provided

I'm working on a Flutter app, that consists of a employee scheduler with a Parse Server background.The app works as the following:
1)User opens the app;
2)The app shows a list of cards of available employees (if there is some in the server database)
3)The user is able to edit, confirm or delete the employee availability.
The app is working. It means that I'm able to CRUD data also from my Parse Server as from my app screen.
The goal: Every data change in the database needs to refresh (realtime) the user screen, removing, deleting or updating the (changed) data itself.
My idea: use parse_server_sdk: ^2.0.1 as a dependency (pubspec.yaml) and implement Live Queries (as the github docs here)
The Problem: after compilation, despite my AndroidStudio don't crashes visually speaking, nor my application itself, it shows me (logs) that "LiveQuery does not work, if there is ParseConnectivityProvider provided".
Without problems(main.dart):
void main() async{
runApp(MyApp());
}
Causing problems:
void main() async{
//the following parameters are in other file (constants.dart)...they are working
Parse().initialize(
kParseApplicationId,
kParseServerUrl,
masterKey: kParseMasterKey,
clientKey: kParseClientKey,
debug: true,
liveQueryUrl: kLiveQueryUrl,
autoSendSessionId: true,
);
var dietPlan = ParseObject('DietPlan')
..set('Name', 'Ketogenic')
..set('Fat', 65);
await dietPlan.save();
var response = await dietPlan.save();
if (response.success) {
dietPlan = response.result;
}
//until here, the program works well.The data is inserted and retrieved, ok...but exactly here..the problem!
final LiveQuery liveQuery = LiveQuery(); //from here..this is causing problems
QueryBuilder<ParseObject> query =
QueryBuilder<ParseObject>(ParseObject('DietPlan'))
..whereEqualTo('intNumber', 1);
Subscription subscription = await liveQuery.client.subscribe(query);
subscription.on(LiveQueryEvent.delete, (value) {
print('*** DELETE ***: ${DateTime.now().toString()}\n $value ');
print((value as ParseObject).objectId);
print((value as ParseObject).updatedAt);
print((value as ParseObject).createdAt);
print((value as ParseObject).get('objectId'));
print((value as ParseObject).get('updatedAt'));
print((value as ParseObject).get('createdAt'));
});
runApp(MyApp());
}
I didn't found any solution googleing.Any at all. After many research, I've got (going deep in the libraries) that Parse.Initialize(...) have connectivityProvider as one of it's parameters, but I didn't fill that parameter.
Also, the problems starts exactly when I've inserted the the line:
final LiveQuery liveQuery = LiveQuery();
Could someone help me to solve this issue?Thanks in advance
In the following, I'm showing all my code(main.dart):
// Copyright 2018 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:intl/intl.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:marca_horario/model/data.dart';
import 'package:marca_horario/network_utils/data_utils.dart';
import 'package:http/http.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
import 'package:marca_horario/constants.dart';
void myLQ() async {
Parse().initialize(
kParseApplicationId,
kParseServerUrl,
masterKey: kParseMasterKey,
clientKey: kParseClientKey,
debug: true,
liveQueryUrl: kLiveQueryUrl,
autoSendSessionId: true,
);
var dietPlan = ParseObject('DietPlan')
..set('Name', 'Ketogenic')
..set('Fat', 65);
await dietPlan.save();
var response = await dietPlan.save();
if (response.success) {
dietPlan = response.result;
}
final LiveQuery liveQuery = LiveQuery();
QueryBuilder<ParseObject> query =
QueryBuilder<ParseObject>(ParseObject('DietPlan'))
..whereEqualTo('intNumber', 1);
Subscription subscription = await liveQuery.client.subscribe(query);
subscription.on(LiveQueryEvent.delete, (value) {
print('*** DELETE ***: ${DateTime.now().toString()}\n $value ');
print((value as ParseObject).objectId);
print((value as ParseObject).updatedAt);
print((value as ParseObject).createdAt);
print((value as ParseObject).get('objectId'));
print((value as ParseObject).get('updatedAt'));
print((value as ParseObject).get('createdAt'));
});
}
void main() async{
Parse().initialize(
kParseApplicationId,
kParseServerUrl,
masterKey: kParseMasterKey,
clientKey: kParseClientKey,
debug: true,
liveQueryUrl: kLiveQueryUrl,
autoSendSessionId: true,
);
var dietPlan = ParseObject('DietPlan')
..set('Name', 'Ketogenic')
..set('Fat', 65);
await dietPlan.save();
var response = await dietPlan.save();
if (response.success) {
dietPlan = response.result;
}
final LiveQuery liveQuery = LiveQuery();
QueryBuilder<ParseObject> query =
QueryBuilder<ParseObject>(ParseObject('DietPlan'))
..whereEqualTo('intNumber', 1);
Subscription subscription = await liveQuery.client.subscribe(query);
subscription.on(LiveQueryEvent.delete, (value) {
print('*** DELETE ***: ${DateTime.now().toString()}\n $value ');
print((value as ParseObject).objectId);
print((value as ParseObject).updatedAt);
print((value as ParseObject).createdAt);
print((value as ParseObject).get('objectId'));
print((value as ParseObject).get('updatedAt'));
print((value as ParseObject).get('createdAt'));
});
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate
],
supportedLocales: [const Locale('pt', 'BR')],
home: Home()
);
}
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
var _listTiles = List<String>();
Color _iconColor = Colors.black;
Color standardIconColor = Colors.black;
Color alternateIconColor = Colors.green;
TextEditingController _nameController = TextEditingController();
var _scaffoldKey = new GlobalKey<ScaffoldState>();
String standardTileTitle = "Adicione um horário disponível...";
String _titleTile = "Adicione um horário disponível...";
String _tileSubtitle = "Edite o nome do funcionário...";
int _selectedIndexBottomNavBar = 0;
final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey = new GlobalKey<RefreshIndicatorState>();
#override
Widget build(BuildContext context) {
return RefreshIndicator(
key: _refreshIndicatorKey,
onRefresh: () async {
setState(() {
});},
child: Scaffold(
key: _scaffoldKey,
floatingActionButton: FloatingActionButton(
onPressed: () {
invokeDatePicker();
},
child: Icon(Icons.add),
),
bottomNavigationBar: bottomNavigationBar(),
appBar: AppBar(
title: Text('Marca Horário'),
),
// body: Center(
// child: Text('Hello World'),
body: bodyStartScreen()
),
);
}
Widget bottomNavigationBar(){
void _onItemTapped(int index) {
setState(() {
_selectedIndexBottomNavBar = index;
});
print(_selectedIndexBottomNavBar);
if(_selectedIndexBottomNavBar == 2){
DatePicker.showDateTimePicker(context,
showTitleActions: true,
minTime: DateTime(2020, 1, 1),
maxTime: DateTime(2021, 12, 31),
onChanged: (date) {
print('change $date');
},
onConfirm: (date) {
print('confirm $date');
_listTiles.add(DateFormat.yMMMEd('pt_BR').add_Hm().format(date).toString());
_titleTile = DateFormat.yMMMEd('pt_BR').add_Hm().format(date).toString();
setState(() {
});
},
currentTime: DateTime.now(),
locale: LocaleType.pt);
}
}
return BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Funcionário',
),
BottomNavigationBarItem(
icon: Icon(Icons.access_time),
label: 'Marcar',
),
],
currentIndex: _selectedIndexBottomNavBar,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
);
}
Widget bodyStartScreen(){
return Column(
children: [
//the main title of the screen
Padding(
padding: EdgeInsets.all(16.0),
child: Text("Horários Possíveis",
style: TextStyle(
fontSize: 18.0
),
),
),
//gets available employees and datetimes from the server
FutureBuilder(builder: (context,snapshot){
if (snapshot.data != null) {
List<Data> dataList = snapshot.data;
return Expanded(
child: ListView.builder(
itemBuilder: (_, position) {
return Card(
child: ListTile(
title: Text(dataList[position].dateTime),
subtitle: Text(dataList[position].employee),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(icon: Icon(Icons.edit), onPressed: () {
//Show dialog box to update item
showUpdateDialog(dataList[position]);
}),
IconButton(icon: Icon(Icons.check_circle, color: Colors.green,), onPressed: () {
}),
//Show dialog box to delete item
IconButton(icon: Icon(Icons.delete), onPressed: () {
deleteData(dataList[position].objectId);
}),
],
),
),
);
},
itemCount: dataList.length,
),
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
future: getDataList(),
),
Divider(
color: Colors.black,
),
scheduleTile()
],
);
}
void invokeDatePicker(){
DatePicker.showDateTimePicker(context,
showTitleActions: true,
minTime: DateTime(2020, 1, 1),
maxTime: DateTime(2021, 12, 31),
onChanged: (date) {
print('change $date');
},
onConfirm: (date) {
print('confirm $date');
_listTiles.add(DateFormat.yMMMEd('pt_BR').add_Hm().format(date).toString());
_titleTile = DateFormat.yMMMEd('pt_BR').add_Hm().format(date).toString();
setState(() {
});
},
currentTime: DateTime.now(),
locale: LocaleType.pt);
}
void showUpdateDialog(Data data) {
_nameController.text = data.employee;
showDialog(context: context,
builder: (_) => AlertDialog(
content: Container(
width: double.maxFinite,
child: TextField(
controller: _nameController,
decoration: InputDecoration(
labelText: "Atualizar funcionário disponível",
),
),
),
actions: <Widget>[
FlatButton(onPressed: () {
Navigator.pop(context);
data.employee = _nameController.text;
updateData(data);
}, child: Text("Atualizar")),
FlatButton(onPressed: () {
Navigator.pop(context);
}, child: Text("Cancelar")),
],
)
);
}
Widget scheduleTile(){
return Padding(
padding: EdgeInsets.only(bottom: 80.0),
child: Card(
color: Colors.grey,
child: ListTile(
title: Text(_titleTile),
subtitle: Text(_tileSubtitle),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
icon: Icon(
Icons.edit,
color: standardIconColor,
size: 20.0,
),
onPressed: () {
setState(() {
employeeAvailable();
});
},
),
IconButton(
icon: Icon(
Icons.check_circle_outline,
color: _iconColor,
size: 20.0,
),
onPressed: () {
setState(() {
(_titleTile != standardTileTitle) ? confirmSchedule() : fillTimeDialog();
});
},
)
],
),
),
),
);
}
void fillTimeDialog(){
showDialog(context: context,
builder: (_) => AlertDialog(
content: Container(
width: double.maxFinite,
child: Text("Insira o horário disponível!"),
),
actions: <Widget>[
FlatButton(onPressed: () {
Navigator.pop(context);
}, child: Text("OK")),
],
)
);
}
void employeeAvailable(){
showDialog(context: context,
builder: (_) => AlertDialog(
content: Container(
width: double.maxFinite,
child: TextField(
controller: _nameController,
decoration: InputDecoration(
labelText: "Funcionário",
),
),
),
actions: <Widget>[
FlatButton(onPressed: () {
Navigator.pop(context);
//addTodo();
setState(() {
_tileSubtitle = "Disponível: " + _nameController.text;
});
}, child: Text("Inserir")),
FlatButton(onPressed: () {
Navigator.pop(context);
setState(() {
_tileSubtitle = " ";
});
}, child: Text("Desfazer")),
],
)
);
}
void confirmSchedule(){
showDialog(context: context,
builder: (_) => AlertDialog(
content: Container(
width: double.maxFinite,
child: Text("Confirma disponibilidade?")
),
actions: <Widget>[
FlatButton(onPressed: () {
Navigator.pop(context);
//addTodo();
addData();
setState(() {
_iconColor = alternateIconColor;
_tileSubtitle = "Disponível: " + _nameController.text;
});
}, child: Text("Confirma")),
FlatButton(onPressed: () {
Navigator.pop(context);
setState(() {
_iconColor = standardIconColor;
_tileSubtitle = " ";
});
}, child: Text("Não")),
],
)
);
}
void addData() {
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Row(
children: <Widget>[
Text("Adicionando informações..."),
CircularProgressIndicator(),
],
mainAxisAlignment: MainAxisAlignment.spaceBetween,
),
duration: Duration(minutes: 1),
));
Data data = Data(employee: _tileSubtitle, dateTime: _titleTile);
DataUtils.addData(data)
.then((res) {
_scaffoldKey.currentState.hideCurrentSnackBar();
Response response = res;
if (response.statusCode == 201) {
//Successful
_nameController.text = "";
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Informações disponibilizadas!"), duration: Duration(seconds: 1),));
setState(() {
//Update UI
});
}
});
}
void deleteData(String objectId) {
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text("Excluindo disponibilidade..."),
CircularProgressIndicator(),
],
),
duration: Duration(minutes: 1),
),);
DataUtils.deleteData(objectId)
.then((res) {
_scaffoldKey.currentState.hideCurrentSnackBar();
Response response = res;
if (response.statusCode == 200) {
//Successfully Deleted
_scaffoldKey.currentState.showSnackBar(SnackBar(content: (Text("Disponibilidade excluída!")),duration: Duration(seconds: 1),));
setState(() {
});
} else {
//Handle error
}
});
}
void updateData(Data data) {
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text("Atualizando disponibilidade..."),
CircularProgressIndicator(),
],
),
duration: Duration(minutes: 1),
),);
DataUtils.updateData(data)
.then((res) {
_scaffoldKey.currentState.hideCurrentSnackBar();
Response response = res;
if (response.statusCode == 200) {
//Successfully Deleted
_nameController.text = "";
_scaffoldKey.currentState.showSnackBar(SnackBar(content: (Text("Disponibilidade atualizada!"))));
setState(() {
});
} else {
//Handle error
}
});
}
Future <List<Data>> getDataList() async{
List<Data> dataList = [];
Response response = await DataUtils.getDataList();
print("Code is ${response.statusCode}");
print("Response is ${response.body}");
if (response.statusCode == 200) {
var body = json.decode(response.body);
var results = body["results"];
for (var data in results) {
dataList.add(Data.fromJson(data));
}
} else {
//Handle error
}
return dataList;
}
}
data_utils.dart:
import 'dart:convert';
import 'package:http/http.dart';
import 'package:marca_horario/model/data.dart';
import 'package:marca_horario/constants.dart';
class DataUtils {
//static final String _baseUrl = "https://parseapi.back4app.com/classes/";
static final String _baseUrl = baseUrl;
//CREATE
static Future<Response> addData(Data data) async {
String apiUrl = _baseUrl + "Data";
Response response = await post(apiUrl,
headers: {
'X-Parse-Application-Id': kParseApplicationId,
'X-Parse-REST-API-Key': kParseRestApiKey,
'Content-Type': 'application/json'
},
body: json.encode(data.toJson()),
);
return response;
}
//READ
static Future getDataList() async{
String apiUrl = _baseUrl + "Data";
Response response = await get(apiUrl, headers: {
'X-Parse-Application-Id' : kParseApplicationId,
'X-Parse-REST-API-Key' : kParseRestApiKey,
});
return response;
}
//UPDATE
static Future updateData(Data data) async{
String apiUrl = _baseUrl + "Data/${data.objectId}";
Response response = await put(apiUrl, headers: {
'X-Parse-Application-Id' : kParseApplicationId,
'X-Parse-REST-API-Key' : kParseRestApiKey,
'Content-Type' : 'application/json',
},
body: json.encode(data.toJson())
);
return response;
}
//DELETE
static Future deleteData(String objectId) async{
String apiUrl = _baseUrl + "Data/$objectId";
Response response = await delete(apiUrl, headers: {
'X-Parse-Application-Id' : kParseApplicationId,
'X-Parse-REST-API-Key' : kParseRestApiKey,
});
return response;
}
}
Problem solved!
My problem was:import 'package:parse_server_sdk/parse_server_sdk.dart';
It needs to be replaced by:import 'package:parse_server_sdk_flutter/parse_server_sdk.dart';
and in pubspec.yaml it's necessary to use only the correspondent dependency:
parse_server_sdk_flutter: ^2.0.1

Flutter JSON data issue

I'm facing issue to fetch json data from Flutter mobile app.
Code as follow:
import 'package:flutter/material.dart';
import 'package:flutter_app/pages/main_page.dart';
class App extends StatelessWidget
{
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: "Flutter NodeJS",
home: MainPage(),
);
}
}
void main(){
runApp(App());
}
main_page.dart
import 'package:flutter/material.dart';
import 'package:flutter_app/modules/http.dart';
import 'package:flutter_app/pages/add_user_page.dart';
class MainPage extends StatefulWidget
{
#override
State<StatefulWidget> createState() {
return MainPageState();
}
}
class User
{
String id;
String first_name,email;
User(this.id, this.first_name,this.email);
}
class MainPageState extends State<MainPage>
{
List<User> users = [];
Future<void> refreshUsers()async{
var result = await http_get('users');
if(result.ok)
{
setState(() {
users.clear();
var in_users = result.data as List<dynamic>;
in_users.forEach((in_user){
users.add(User(
in_user['id'].toString(),
in_user['first_name'],
in_user['email']
));
});
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Users"),
//email: Text("Email"),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: (){
Navigator.of(context).push(MaterialPageRoute(
builder: (context){
return AddUserPage();
}
));
},
)
],
),
body: RefreshIndicator(
onRefresh: refreshUsers,
child: ListView.separated(
itemCount: users.length,
itemBuilder: (context, i) => ListTile(
leading: Icon(Icons.person),
title: Text(users[i].first_name+"\n" + users[i].email),
//email: Text(users[i].email),
),
separatorBuilder: (context, i) => Divider(),
),
),
);
}
}
http.dart
import 'dart:convert';
import "package:http/http.dart" as http;
class RequestResult
{
bool ok;
dynamic data;
RequestResult(this.ok, this.data);
}
//'https://jsonplaceholder.typicode.com/users/1
//http://192.168.183.179:8081/api/users/
const PROTOCOL = "http";
const DOMAIN = "https://jsonplaceholder.typicode.com/users/1";
Future<RequestResult> http_get(String route, [dynamic data]) async
{
var dataStr = jsonEncode(data);
var url = "$PROTOCOL://$DOMAIN/$route?data=$dataStr";
var result = await http.get(url);
return RequestResult(true, jsonDecode(result.body));
}
Future<RequestResult> http_post(String route, [dynamic data]) async
{
var url = "$PROTOCOL://$DOMAIN/$route";
var dataStr = jsonEncode(data);
var result = await http.post(url, body: dataStr, headers:{"Content-Type":"application/json"});
return RequestResult(true, jsonDecode(result.body));
}
When I'm fetch json data from "https://jsonplaceholder.typicode.com/users/1". Its working fine.
enter image description here
When I try to fetch json data from "https://192.168.183.179:8081/api/users". Its give error:
at Object.createErrorWithStack (http://localhost:15340/dart_sdk.js:4348:12)
at Object._rethrow (http://localhost:15340/dart_sdk.js:37892:16)
at async._AsyncCallbackEntry.new.callback (http://localhost:15340/dart_sdk.js:37886:13)
at Object._microtaskLoop (http://localhost:15340/dart_sdk.js:37718:13)
at _startMicrotaskLoop (http://localhost:15340/dart_sdk.js:37724:13)
at http://localhost:15340/dart_sdk.js:33243:9
What I'm doing wrong
Regards,
SAO
Check in Postman whether the ip address is returning data.
Another case would be the data obtained, could not be transffered correctly to the app. Check the variables and types where the data is stored.

Resources