I'm using this package sunmi_printer_plus.
Here my code
await SunmiPrinter.bindingPrinter();
await SunmiPrinter.initPrinter();
await SunmiPrinter.startTransactionPrint(true);
await SunmiPrinter.printText(
restaurant.title,
style: SunmiStyle(
align: SunmiPrintAlign.CENTER,
),
);
await SunmiPrinter.lineWrap(1);
await SunmiPrinter.printText(
'ใบเสร็จ',
style: SunmiStyle(
align: SunmiPrintAlign.CENTER,
),
);
await SunmiPrinter.line();
await SunmiPrinter.printRow(cols: [
ColumnMaker(text: 'NO:', width: 10, align: SunmiPrintAlign.LEFT),
ColumnMaker(text: order.id, width: 20, align: SunmiPrintAlign.RIGHT),
]);
await SunmiPrinter.printRow(cols: [
ColumnMaker(text: 'Time:', width: 10, align: SunmiPrintAlign.LEFT),
ColumnMaker(
text: DateFormat('dd/MM/yyyy HH:mm')
.format(order.paidTime ?? DateTime.now()),
width: 20,
align: SunmiPrintAlign.RIGHT),
]);
await SunmiPrinter.line();
await SunmiPrinter.bold();
await SunmiPrinter.printRow(cols: [
ColumnMaker(text: 'Menu', width: 15, align: SunmiPrintAlign.LEFT),
ColumnMaker(text: 'Price', width: 15, align: SunmiPrintAlign.RIGHT),
]);
await SunmiPrinter.resetBold();
for (var item in order.cart.items) {
await SunmiPrinter.printRow(cols: [
ColumnMaker(
text: '${item.amount} x ${item.product.title}',
width: 20,
align: SunmiPrintAlign.LEFT),
ColumnMaker(
text: item.totalPrice.toString(),
width: 10,
align: SunmiPrintAlign.RIGHT),
]);
}
await SunmiPrinter.line();
await SunmiPrinter.printRow(cols: [
ColumnMaker(text: 'Total', width: 10, align: SunmiPrintAlign.LEFT),
ColumnMaker(
text: '฿${order.cart.totalPrice}',
width: 20,
align: SunmiPrintAlign.RIGHT),
]);
await SunmiPrinter.lineWrap(1);
await SunmiPrinter.printText(
'ขอบคุณที่มาอุดหนุนค่ะ',
style: SunmiStyle(
align: SunmiPrintAlign.CENTER,
fontSize: SunmiFontSize.SM,
),
);
await SunmiPrinter.printText(
'Powered by Dr.Dish',
style: SunmiStyle(
align: SunmiPrintAlign.CENTER,
fontSize: SunmiFontSize.SM,
),
);
await SunmiPrinter.lineWrap(3);
await SunmiPrinter.exitTransactionPrint(true);
Here result
as you can see, the character is stack on each other on lines that use printRow. (printText working fine)
and it working fine when I change to English.
What do I miss or this is a bug? I tried to change column size and word length, but still not working.
Related
here are my function name fetchPrayerData() and inside the function i want to count the data how many subuh that are "Prayed On Time, "Prayed Late", and "Not Prayed" and display the data in the pie chart but, unfortunately the data count won't display in the pie chart although there is no error in the code.
Future<List<PieChartSectionData>> fetchPrayerData() async {
double subuhPrayed = 0;
double subuhPrayedLate = 0;
double subuhNotPrayed = 0;
// subuhPrayed = prayedOnTimeQuerySnapshot.docs.length.toDouble();
// subuhPrayedLate = prayedLateQuerySnapshot.docs.length.toDouble();
// subuhNotPrayed = notPrayedQuerySnapshot.docs.length.toDouble();
FirebaseFirestore.instance
.collection('record_prayer')
.where('prayerName', isEqualTo: 'subuh')
.where('dailyPrayerStatus', isEqualTo: 'Prayed On Time')
.count()
.get()
.then((querySnapshot) => subuhPrayed = querySnapshot.count.toDouble());
FirebaseFirestore.instance
.collection('record_prayer')
.where('prayerName', isEqualTo: 'subuh')
.where('dailyPrayerStatus', isEqualTo: 'Prayed Late')
.count()
.get()
.then(
(querySnapshot) => subuhPrayedLate = querySnapshot.count.toDouble());
FirebaseFirestore.instance
.collection('record_prayer')
.where('prayerName', isEqualTo: 'subuh')
.where('dailyPrayerStatus', isEqualTo: 'Not Prayed')
.count()
.get()
.then((querySnapshot) => subuhNotPrayed = querySnapshot.count.toDouble());
return [
PieChartSectionData(
color: Colors.green,
value: subuhPrayed,
//title: '$prayedOnTimeQuerySnapshot',
title: '${(subuhPrayed * 100).toStringAsFixed(0)}%',
radius: 60,
titleStyle: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
PieChartSectionData(
color: Colors.yellow,
value: subuhPrayedLate,
//title: '',
title: '${(subuhPrayedLate * 100).toStringAsFixed(0)}%',
radius: 60,
titleStyle: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
PieChartSectionData(
color: Colors.red,
value: subuhNotPrayed,
title: '${(subuhNotPrayed * 100).toStringAsFixed(0)}%',
radius: 60,
titleStyle: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
];
}
here are the stateful widget that i want to display the data in the pie chart but, it wont display the data that count from the function.
Expanded(
child: FutureBuilder<
List<PieChartSectionData>>(
future: fetchPrayerData(),
builder: (context, snapshot) {
if (snapshot.hasData &&
snapshot.data != null) {
return AspectRatio(
aspectRatio: 1,
child: PieChart(
PieChartData(
pieTouchData: PieTouchData(
touchCallback: (FlTouchEvent
event,
pieTouchResponse) {},
),
borderData: FlBorderData(
//show: false;
),
sectionsSpace: 0,
centerSpaceRadius: 40,
sections: snapshot.data!,
),
),
);
}
return const CircularProgressIndicator();
},
),
),
I hope you guys are happy and healthy
I am facing a problem in flutter
i will be very thankful to you if any of you help me resolving this issue
I am trying to fetch data from api
and show it in alphabetic list with the help of stream builder
but i am getting the same data multiple of time
let me show you the code
here i am trying to fetch data from api and convert it into list
Future<List<DisplayClients>> getClientList() async {
String email = widget.email;
final response = await http.get(
Uri.parse(
api),
);
if (response.statusCode == 200) {
final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
var list = parsed
.map<DisplayClients>(
(json) => DisplayClients.fromMap(json),
)
.toList();
print('clientList');
print(list.length);
for (var i = 0; i < list.length; i++) {
clientList.add(AlphabetSearchModel(
title: list[i].name,
subtitle: list[i].email,
phoneNumber: list[i].phoneNumber));
}
print(clientList);
return parsed
.map<DisplayClients>(
(json) => DisplayClients.fromMap(json),
)
.toList();
} else {
throw Exception('Failed to load album');
}
}
here i am showing i am using data in streamBuilder
StreamBuilder<List<DisplayClients>>(
stream: getClientsStream(),
builder: (context, snapshot) {
if (snapshot.hasData) {
// var list = s
print('got data');
print(snapshot.data!.length);
return SizedBox(
height: MediaQuery.of(context).size.height * 0.7,
child: AlphabetSearchView.modelList(
list: clientList,
buildItem: (context, index, item) {
return Padding(
padding:
const EdgeInsets.symmetric(vertical: 6),
child: Card(
// margin: EdgeInsets.all(12),
elevation: 3,
color: Constants.purpleLight,
shadowColor: Colors.white,
child: Row(children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: LinearGradient(
colors: [
Constants.red,
Constants.orange,
],
begin: Alignment.bottomLeft,
end: Alignment.topRight)),
child: CircleAvatar(
radius: 40,
child: Icon(
Icons.person,
color: Colors.white,
size: 40,
),
backgroundColor:
Colors.transparent),
),
),
SizedBox(
width: 10,
),
CustomText(
text: item.title,
color: Colors.white,
size: 18,
weight: FontWeight.w400,
),
SizedBox(
width: 10,
),
CircleAvatar(
backgroundColor: Constants.orange,
radius: 4,
),
SizedBox(
width: 10,
),
CustomText(
text: item.subtitle,
color: Colors.white70,
size: 14,
weight: FontWeight.w400,
),
SizedBox(
width: 10,
),
CircleAvatar(
backgroundColor: Constants.orange,
radius: 4,
),
SizedBox(
width: 10,
),
CustomText(
text: item.phoneNumber,
color: Colors.white70,
size: 14,
weight: FontWeight.w400,
),
Spacer(),
Padding(
padding: const EdgeInsets.all(12),
child: primaryButton(
verticalPadding: 0,
context: context,
text: 'Deal with ${item.title}',
onTap: () {
Navigator.push(context,
MaterialPageRoute(
builder: (context) {
return SeperateClient(
clientName: item.title,
email: widget.email,
clientEmail:
item.subtitle!);
}));
}),
)
])));
},
)
);
}
return Container();
},
)
i am calling getClientList() method in initSate
here is code for getClientStream()
Stream<List<DisplayClients>> getClientsStream() async* {
while (true) {
await Future.delayed(Duration(milliseconds: 1));
yield await getClientList();
}
}
this code is returning multiple data's
please let me know where i am making mistakes
i will be thankful to you
Thanks :)
Try the following code:
Stream<List<DisplayClients>> getClientsStream() async* {
await Future.delayed(const Duration(milliseconds: 1));
String email = widget.email;
final response = await http.get(
Uri.parse(api),
);
if (response.statusCode == 200) {
final parsed = json.decode(response.body).cast<Map<String, dynamic>>();
var list = parsed
.map<DisplayClients>(
(json) => DisplayClients.fromMap(json),
)
.toList();
print('clientList');
print(list.length);
for (var i = 0; i < list.length; i++) {
clientList.add(AlphabetSearchModel(title: list[i].name, subtitle: list[i].email, phoneNumber: list[i].phoneNumber));
}
print(clientList);
yield* parsed
.map<DisplayClients>(
(json) => DisplayClients.fromMap(json),
)
.toList();
} else {
throw Exception('Failed to load album');
}
}
I am trying to connect different wallets using the Wallet_connect package. However, Every time I click on a different wallet, it opens the same one like all the buttons open Metamask, or all of them open Trust Wallet. I am new to Flutter and to web3 generally
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:walletconnect_dart/walletconnect_dart.dart';
class Connect extends StatefulWidget {
const Connect({Key? key}) : super(key: key);
#override
State<Connect> createState() => _ConnectState();
}
class _ConnectState extends State<Connect> {
var connector = WalletConnect(
bridge: 'https://bridge.walletconnect.org',
clientMeta: const PeerMeta(
name: 'IRISA ++',
description: 'WalletConnect Developer App',
url: 'https://metamask.io/',
icons: [
'https://files.gitbook.com/v0/b/gitbook-legacy-files/o/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media'
]));
loginUsingMetamask(BuildContext context) async {
if (!connector.connected) {
try {
var session = await connector.createSession(onDisplayUri: (uri) async {
var _uri = uri;
await launchUrlString(uri, mode: LaunchMode.externalApplication);
});
print(session.accounts[0]);
print(session.chainId);
setState(() {
var _session = session;
});
} catch (exp) {
print(exp);
}
}
}
loginUsingTrust(BuildContext context) async {
if (!connector.connected) {
try {
var session = await connector.createSession(onDisplayUri: (uri) async {
await launchUrlString(uri, mode: LaunchMode.externalApplication);
});
setState(() {
});
} catch (exp) {
print(exp);
}
}
}
loginUsingRain(BuildContext context) async {
if (!connector.connected) {
try {
var session = await connector.createSession(onDisplayUri: (uri) async {
await launchUrlString(uri, mode: LaunchMode.externalApplication);
});
setState(() {
});
} catch (exp) {
print(exp);
}
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white, //<-- SEE HERE
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('lib/assets/images/wallet.png', width:400, height:200),
const SizedBox(
height: 60,
child:Text('Connect your wallet', style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Colors.black)),
),
SizedBox(
width: 300, // <-- Your width
height: 100, // <-- Your height
child: ElevatedButton.icon(// <-- OutlinedButton
onPressed: () => loginUsingMetamask(context),
icon:Image.asset('lib/assets/images/metamask.png', width:50, height:50),
label: const Text('MetaMask', style: TextStyle(
fontSize: 28,
color: Colors.white)),
style: ElevatedButton.styleFrom(
primary: Colors.brown,
side: BorderSide(color: Colors.brown.shade900, width: 3), //<-- SEE HERE
),//elevated btton background
),
),
const SizedBox(
height: 10,
),
SizedBox(
width: 300, // <-- Your width
height: 100, // <-- Your height
child: OutlinedButton.icon( // <-- OutlinedButton
onPressed: () => loginUsingTrust(context),
icon: Image.asset('lib/assets/images/trustwallet1.png', width:50, height:50),
label: const Text('Trust Wallet', style: TextStyle(
fontSize: 28,
color: Colors.white)),
style: ElevatedButton.styleFrom(
primary: Colors.grey.shade400,
side: BorderSide(color: Colors.blue.shade900, width: 3), //<-- SEE HERE
),
),
),
const SizedBox(
height: 10,
),
SizedBox(
width: 300, // <-- Your width
height: 100, // <-- Your height
child: OutlinedButton.icon( // <-- OutlinedButton
onPressed: () => loginUsingRain(context),
icon:Image.asset('lib/assets/images/rainbow.png', width:50, height:50),
label: const Text('Rainbow', style: TextStyle(
fontSize: 28,
color: Colors.white)),
style: ElevatedButton.styleFrom(
primary: Colors.blue,
side: BorderSide(color: Colors.blue.shade900, width: 3), //<-- SEE HERE
),
),
),
],
),
)
);
}
}
I would really appreciate any response or different way to do this task
Thank you
So I have an app where I have images stored on Firebase Storage and I want to loop through a few records in my Firestore and create Containers() for each of them to be used in a PageView. However, when looping through it seems like the AWAIT clues are ignored somehow?
This is what I got:
loadDashboard() async {
// Load data about breed in focus
Map<String, dynamic> _documentData;
_isLoadingArticles = true;
_dashboardArticles.clear();
int _articleCount = 0;
await _firestore
.collection('DashboardArticle')
.where("active", isEqualTo: true)
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
_articleCount++;
downloadURL(doc["image"]);
print(doc["title"]);
_dashboardArticles.add(
Padding(
padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
child: Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(15),
child: Image(
image: NetworkImage(
_articleImgUrl,
),
alignment: Alignment.center,
width: double.infinity,
fit: BoxFit.cover,
),
),
Padding(
padding: EdgeInsets.fromLTRB(20, 10, 0, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 25),
Text(
doc["title"],
style: TextStyle(
shadows: [
Shadow(
blurRadius: 10.0,
color: Colors.black,
offset: Offset(1.0, 1.0),
),
],
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold),
),
SizedBox(height: 5),
Text(
doc["tagline"],
style: TextStyle(
color: Colors.white,
fontSize: 16,
shadows: [
Shadow(
blurRadius: 10.0,
color: Colors.black,
offset: Offset(1.0, 1.0),
),
],
),
)
],
),
),
],
),
),
);
setState(() {
_isLoadingArticles = false;
_totalArticleDots = _articleCount;
});
});
}).catchError((e) => print("error fetching data: $e"));
}
Future<String> downloadURL(String image) async {
await firebase_storage.FirebaseStorage.instance
.ref('dashboard_article_images/$image')
.getDownloadURL()
.then((value) => {
setState(() {
_articleImgUrl = value;
print(_articleImgUrl);
})
})
.catchError((e) => {
setState(() {
_articleImgUrl = "";
})
});
return "";
}
_articleImgUrl is a variable outside that I set as I'm not sure how to get the String value from the Future in any other way.
Each PRINT shows the data in correct order, for example:
flutter: Pooch in focus: Corgi
flutter: https://firebasestorage.googleapis.com:443/v0/b/.../o/article_images%2F4f3... (I truncated here)
When I se breakpoints it seems that _articleImgUrl has no value at the time the _dashboardArticles.add(...) is executed, so it feels like the awaits are skipped when looping somehow?
Invalid argument(s): No host specified in URI file:///
Can anyone provide insights? Thanks!
Yes your await is ignored because you are not awaiting your method downloadURL, also I would not recommend to use querySnapshot.docs.forEach as you won't be able to manage asynchronous operations correctly. You should use for in instead, also you should not use await and then at the same time.
Here is some fix you could apply to your code:
final querySnapshot = await _firestore
.collection('DashboardArticle')
.where("active", isEqualTo: true)
.get().catchError((e) => print("error fetching data: $e"));
for (final doc in querySnapshot.docs) {
_articleCount++;
await downloadURL(doc['image']);
print(doc["title"]);
// rest of your loop ...
}
By doing so you ensure all of your asynchronous operations are correctly awaited.
I need to setState the showDialog() from the outside. The showDialog() shows how many images are uploaded to Firestore. But setState is not working because it doesn't change the state of showDialog(). Is there any way to change the state of showDialog() from outside??
Here is my code.
Future<void> _upload() async {
Reference storageReference;
showDialog(
context: context,
builder: (context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10)),
side: BorderSide(width: 1, color: Colors.white),
),
contentPadding: EdgeInsets.all(20),
content: SizedBox(
height: 150,
width: 180,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
SpinKitRing(
color: Color(0xff43b0e2),
lineWidth: 10,
size: 100,
),
// here is the part I want to setState
Text("$value/${widget.imagelist.length + 1}",
style: TextStyle(
color: Color(0xff43b0e2),
fontWeight: FontWeight.w800,
fontFamily: "Montserrat",
fontStyle: FontStyle.normal,
fontSize: 18.0),
textAlign: TextAlign.center),
],
),
),
backgroundColor: Colors.grey.withOpacity(0.9),
);
},
);
for (File image in widget.imagelist) {
storageReference = FirebaseStorage.instance.ref().child('project/' +
FirebaseAuth.instance.currentUser.uid +
"/" +
widget.title +
"/" +
image.path.toString().split("/").last);
await storageReference.putFile(image);
String downloadURL = await storageReference.getDownloadURL();
setState(() {
imglist.add(downloadURL);
value += 1;
});
}
storageReference = FirebaseStorage.instance.ref().child('project/' +
FirebaseAuth.instance.currentUser.uid +
"/" +
widget.title +
"/thumbnail");
await storageReference.putFile(widget.thumbnail);
String thumbnailURL = await storageReference.getDownloadURL();
setState(() {
value += 1;
});
await FirebaseFirestore.instance.collection('Gallery').add({
"author": FirebaseAuth.instance.currentUser.uid,
"bookmark": <String>[],
"description": widget.description,
"image": imglist,
"liked": <String>[],
"time": Timestamp.fromDate(DateTime.now()),
"title": widget.title,
"visited": 0,
"is18": widget.is18,
"object": widget.objlist,
"tool": widget.toollist,
"thumbnail": thumbnailURL,
"tag": widget.taglist,
"platform": widget.platform,
});
Navigator.of(context).pop();
}
use valueNotifier
when image uploaded make notifier.value++;
and in showDialog add widget :
ValueListenableBuilder<int>(
valueListenable:notifier,
builder:(ctx,value,child){
return Text("$value/${widget.imagelist.length + 1}",
style: TextStyle(
color: Color(0xff43b0e2),
fontWeight: FontWeight.w800,
fontFamily: "Montserrat",
fontStyle: FontStyle.normal,
fontSize: 18.0),
textAlign: TextAlign.center);
}
);