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();
},
),
)
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',
},
}
I am still new to flutter and am learning building apps. I have been trying to run this code for but every time I run it I get a red screen on the android emulator and an error which goes "Failed Assertion: Line 22 pos 14 'url != null': is not true".
This is my main file which runs the app
import "package:flutter/material.dart";
import "src/app.dart";
voidmain() {
runApp(MyApp());
}
My App file has this code
import 'package:flutter/material.dart';
import 'package:http/http.dart' show get;
import 'models/image_models.dart';
import 'dart:convert';
import 'widgets/image_list.dart';
class MyApp extends StatefulWidget {
createState() {
return AppState();
}
}
class AppState extends State<MyApp> {
int counter = 0;
List<ImageModels> images = [];
void fetchImage() async {
counter++;
var response =
await get('http://jsonplaceholder.typicode.com/photos/$counter');
var imagemodel = ImageModels.fromjson(json.decode(response.body));
setState(() {
images.add(imagemodel);
});
}
Widget build(context) {
return MaterialApp(
home: Scaffold(
body: ImageList(images),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
fetchImage();
}),
appBar: AppBar(title: Text("Ola Amigo!")),
));
}
}
Heres the ImageModel Class
class ImageModels {
int id;
String url;
String title;
ImageModels(this.id, this.url, this.title);
ImageModels.fromjson(Map<String, dynamic> parsedjson) {
id = parsedjson[id];
title = parsedjson[title];
url = parsedjson[url];
}
}
and lastly the ImageList
import 'package:flutter/material.dart';
import '../models/image_models.dart';
class ImageList extends StatelessWidget {
final List<ImageModels> image;
ImageList(this.image);
Widget build(context) {
return ListView.builder(
itemCount: image.length,
itemBuilder: (context, int index) {
return buildImage(image[index]);
});
}
Widget buildImage(ImageModels image) {
return Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey)
),
padding: EdgeInsets.all(20.0),
margin: EdgeInsets.all(20.0),
child: Image.network(image.url),
);
}
}
Can someone please take a look at it and tell me what am I doing wrong and how can I resolve this issue.
Thank you
You can copy paste run full code below
You have error in ImageModels, please revise to
code snippet
factory ImageModels.fromjson(Map<String, dynamic> parsedjson) => ImageModels(
parsedjson["id"],
parsedjson["url"],
parsedjson["title"],
);
working demo
full code
import 'dart:convert';
import 'package:http/http.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
createState() {
return AppState();
}
}
class AppState extends State<MyApp> {
int counter = 0;
List<ImageModels> images = [];
void fetchImage() async {
counter++;
var response =
await get('https://jsonplaceholder.typicode.com/photos/$counter');
print(response.body);
var imagemodel = ImageModels.fromjson(json.decode(response.body));
print(imagemodel.url);
setState(() {
images.add(imagemodel);
print(images[0].url);
});
}
Widget build(context) {
return MaterialApp(
home: Scaffold(
body: ImageList(images),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
fetchImage();
}),
appBar: AppBar(title: Text("Ola Amigo!")),
));
}
}
class ImageModels {
int id;
String url;
String title;
ImageModels(this.id, this.url, this.title);
factory ImageModels.fromjson(Map<String, dynamic> parsedjson) => ImageModels(
parsedjson["id"],
parsedjson["url"],
parsedjson["title"],
);
}
class ImageList extends StatelessWidget {
final List<ImageModels> image;
ImageList(this.image);
Widget build(context) {
return ListView.builder(
itemCount: image.length,
itemBuilder: (context, int index) {
print(image[index].url);
return buildImage(image[index]);
});
}
Widget buildImage(ImageModels image) {
return Container(
decoration: BoxDecoration(border: Border.all(color: Colors.grey)),
padding: EdgeInsets.all(20.0),
margin: EdgeInsets.all(20.0),
child: Image.network(image.url),
);
}
}
I tried to print in a ZEBRA ez320 Bluetooth printer I found out that it only works using cpcl code, the good news is I have the sample code for cpcl but I don't know how to integrate it on my Flutter project.
Can someone help me out?
This github https://github.com/devinim/flutter-zsdk has Zebra SDK Kit Flutter Integration
code snippet
devices = await FlutterZsdk.discoverBluetoothDevices();
devices.forEach((d) {
print('Device: ${d.friendlyName} [${d.mac}]');
});
...
d.sendZplOverBluetooth(FLUTTER_LOGO_ZPL),
full example code https://github.com/devinim/flutter-zsdk/blob/master/example/lib/main.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter_zsdk/flutter_zsdk.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
static const String FLUTTER_LOGO_ZPL = "^XA^CI28^PON^PW560^MNN^LL460^LH0,0^LT60" +
"^GFA,6150,6150,25,,gP01XFCgP03XF8gP07XF,gP0XFE,gO01XFC,gO03XF8,gO07XF,gO0XFE,gN01XFC,gN03XF8,gN0YF,gN0XFE,gM01XFC,gM03XF8,gM0YF,gL01XFE"
",gL01XFC,gL07XF8,gL0YF,gK01XFE,gK03XFC,gK07XF8,gK0YF,gJ01XFE,gJ03XFC,gJ07XF8,gJ0YF,gI01XFE,gI03XFC,gI07XF8,gI0YF,gH01XFE,gH03XFC,gH07XF8"
",gH0YF,gG01XFE,gG03XFC,gG07XF8,gG0YF,g01XFE,g03XFC,g07XF8,g0YF,Y01XFE,Y03XFC,Y07XF8,Y0YF,X01XFE,X03XFC,X07XF8,X0YF,W01XFE,W03XFC,W07XF8"
",W0YF,V01XFE,V03XFC,V07XF8,V0YF,U01XFE,U03XFC,U07XF8,U0YF,T01XFE,T03XFC,T07XF8,T0YF,S01XFE,S03XFC,S07XF8,S0YF,R01XFE,R03XFC,R07XF8"
",R0YF,Q01XFE,Q03XFC,Q07XF8,Q0YF,P01XFE,P03XFC,P07XF8,P0YF,O01XFE,O03XFC,O07XF8,O0YF,N01XFE,N03XFC,N07XF8,N0YF,M01XFE,M03XFC,M07XF8"
",M0YF,L01XFE,L03XFC,L07XF8,L0YF,K01XFE,K03XFC,K07XF8,K0YF,J01XFE,J03XFC,J07XF8,J0YF,I01XFE,I03XFC,I07XF8,I0XFE,001XFE,003XFCN03XF"
",007XF8N07XF,00XFEO0XFE,01XFCN01XFC,03XFCN03XF8,07XF8N07XF,0XFEO0XFE,1XFCN01XFC,3XF8N03XF8,7XF8N07XF,3WFEO0XFE,1WFCN01XFC,0WF8N03XF8"
",07VFO07XF,03UFEO0XFE,01UFCN01XFC,00UF8N03XF8,007TFO07XF,003SFEO0XFE,001SFCN01XFC,I0SF8N03XF8,I07RFO07XF,I03QFEO0XFE,I01QFCN01XFC,J0QF8N03XF8"
",J07PFO07XF,J03OFEO0XFE,J01OFCN01XFC,K0OF8N03XF8,K07NFO07XF,K03MFEO0XFE,K01MFCN01XFC,L0MF8N03XF8,L07LFO07XF,L03KFEO0XFE,L01KFCN01XFC,M0KF8N03XF8"
",M07JFO07XF,M03IFEO0XFE,M01IFCN01XFC,N0IF8N03XF8,N07FFO07XF,N03FEO0XFE,N01FCN01XFC,O0F8N03XF8,O07O07XF,O02O0XFE,X01XFC,X03XF8,X07XF,X0XFE,W01XFC"
",W03XF8,W07XF,W0XFE,V01XFC,V03XF8,V07XF,V0XFE,U01XFC,U03XF8,U07XF,U0XFE,T01XFC,T07XF8,T07XF,T03XF8,T01XFC,U0XFE,U07XF,U03XF8,U01XFC,V0XFE,V07XF"
",V03XF8,V01XFC,W0XFE,W07XF,W07XF8,W03XFC,X0XFE,X07XF,X07XF8,X03XFC,X01XFE,Y07XF,Y07XF8,Y03XFC,Y01XFE,g0YF,g07XF8,g03XFC,g01XFE,gG0YF,gG07XF8,gG03XFC"
",gG01XFE,gH0YF,gH07XF8,gH03XFC,gH01XFE,gI0YF,gI07XF8,gI03XFC,gI01XFC,gJ0XFE,gJ07XF,gJ03XF8,gJ01XFC,gK0XFE,gK07XF,gK03XF8,gK01XFC,gL0XFE,gL07XF,gL03XF8"
",gL01XFC,gM0XFE,gM07XF,gM03XF8,gM01XFC,gN0XFE,gN07XF,gN03XF8,gN01XFC,gO0XFE,gO07XF,gO03XF8,gO01XFC,gP0XFE,gP07XF,gR01VF8"
",^FS ^XZ";
List<ZebraBluetoothDevice> _devices = List();
#override
void initState() {
super.initState();
__init();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> __init() async {
List<ZebraBluetoothDevice> devices = List();
try {
devices = await FlutterZsdk.discoverBluetoothDevices();
devices.forEach((d) {
print('Device: ${d.friendlyName} [${d.mac}]');
});
} catch (e) {
showDialog(context: context, child: Text(e));
//throw e;
print('Error' + e);
}
if (!mounted) return;
setState(() {
_devices = devices;
});
}
String levelText = "Querying...";
_level(ZebraBluetoothDevice d) {
d.batteryLevel().then((t) {
setState(() {
levelText = t;
});
});
}
Widget _listPrinters() {
List<Widget> items = List();
if (_devices.length < 1) {
items.add(ListTile(
title: Text("Not found any or still searching"),
));
} else {
items.addAll([
ListTile(
title: Text("Found ${_devices.length} device(s)"),
),
SizedBox(height: 50),
]);
_devices.forEach((d) {
_level(d);
items.add(
ListTile(
title: Text(d.friendlyName),
subtitle: Text(d.mac + "[%${levelText}]"),
leading: IconButton(icon: Icon(Icons.list), onPressed: () => d.properties()),
trailing: IconButton(
icon: Icon(Icons.print),
onPressed: () => d.sendZplOverBluetooth(FLUTTER_LOGO_ZPL),
),
),
);
});
}
return ListView(
padding: EdgeInsets.all(24),
children: items,
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Zebra Plugin Example App'),
),
body: _listPrinters(),
),
);
}
}