The issue is in product price - flutter

i dont know what the issue in my code
but when i remain 2 quantity and 200 price and go back and go to cart and i press add icon it show 400 price and 2 quantity but i want 3quantity and 300 price
I think issue is in updating product price and quantity .I don't know what the error.Please anyone who solve the issue ?
Here is my code
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
snapshot.data!.docs[index]["Productname"],
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
SizedBox(height: 8),
Row(
children: [
Text(
"${int.parse(snapshot.data!.docs[index]["productprice"].toString())*snapshot.data!.docs[index]["quantity"]}",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
SizedBox(width: 16),
IconButton(
icon: Icon(Icons.remove),
onPressed: ()async{
setState(() {
if (_quantity>1) {
_quantity--;
}
});
await FirebaseFirestore.instance
.collection('Cart')
.doc(snapshot.data!.docs[index].id) // Use the document ID as the unique identifier
.update({'quantity': _quantity});
},
),
SizedBox(width: 8),
Text(
"${snapshot.data!.docs[index]["quantity"]}",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
SizedBox(width: 8),
IconButton(
icon: Icon(Icons.add),
onPressed: ()async{
setState(() {
_quantity++;
});
await FirebaseFirestore.instance
.collection('Cart')
.doc(snapshot.data!.docs[index].id) // Use the document ID as the unique identifier
.update({'quantity': _quantity});
var newPrice = int.parse(snapshot.data!.docs[index]["productprice"].toString()) * snapshot.data!.docs[index]["quantity"];
await FirebaseFirestore.instance
.collection('Cart')
.doc(snapshot.data!.docs[index].id)
.update({'productprice': newPrice});
},
),
],
),
],
),

You are updating the productPrice as well in the place of updating only quantity
You should remove following two lines in add button
var newPrice = int.parse(snapshot.data!.docs[index]["productprice"].toString()) * snapshot.data!.docs[index]["quantity"];
await FirebaseFirestore.instance
.collection('Cart')
.doc(snapshot.data!.docs[index].id)
.update({'productprice': newPrice});
Your add button code should be as following
IconButton(
icon: Icon(Icons.add),
onPressed: ()async{
setState(() {
_quantity++;
});
await FirebaseFirestore.instance
.collection('Cart')
.doc(snapshot.data!.docs[index].id) // Use the document ID as the unique identifier
.update({'quantity': _quantity});
},
)

Related

The issue is with incriment quantity ,decriment quantity and product price

When I pressed one button The other buttons automatically pressed .I don't know the issue .
And the second is with product price when i incriment the item the price become 100100 if i have price 100
Please solve my issues.
Here is my code
int _quantity=1;
Stream builder
StreamBuilder(
stream: FirebaseFirestore.instance.collection("Cart").where("id",isEqualTo:FirebaseAuth.instance.currentUser!.uid).snapshots(),
builder:(BuildContext context,AsyncSnapshot<QuerySnapshot>snapshot){
if (!snapshot.hasData) {
return Center(child: LoadingAnimationWidget.staggeredDotsWave(color: Colors.red, size: 100));
}
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (itemBuilder,index){
return Padding(
padding: const EdgeInsets.all(8.0),
Product price
child: Card(
child: Container(
child: Row(
children: [
Row(
children: [
Text(
"${ snapshot.data!.docs[index]["productprice"]*_quantity}",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
SizedBox(width: 16),
IconButton(
icon: Icon(Icons.remove),
onPressed: (){
setState(() {
if (_quantity>1) {
_quantity--;
}
});
},
),
SizedBox(width: 8),
Text(
"$_quantity",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
SizedBox(width: 8),
IconButton(
icon: Icon(Icons.add),
onPressed: (){
setState(() {
_quantity++;
});
},
),
],
),
],
),
],
),
),
)));
});
} ,
),
Looks you have a String value in snapshot.data!.docs[index]["productprice"]. You should convert String to double or int before multiplication.
So you code should look as following
Text(
"${ double.parse(snapshot.data!.docs[index]["productprice"].toString()) * _quantity}",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
Edited:
If you want to manage with multiple items, then introduce one field final Map<String, int> quantity = <String, int>{};
StreamBuilder(
stream: FirebaseFirestore.instance.collection("Cart").where("id",isEqualTo:FirebaseAuth.instance.currentUser!.uid).snapshots(),
builder:(BuildContext context,AsyncSnapshot<QuerySnapshot>snapshot){
if (!snapshot.hasData) {
return Center(child: LoadingAnimationWidget.staggeredDotsWave(color: Colors.red, size: 100));
}
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (itemBuilder,index){
final doc = snapshot.data!.docs[index];
final _quantity = quantity[doc.id] ?? 0;
return Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
child: Container(
child: Row(
children: [
Row(
children: [
fina;
Text(
"${doc["productprice"]*_quantity}",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
SizedBox(width: 16),
IconButton(
icon: Icon(Icons.remove),
onPressed: (){
if (_quantity>1) {
setState(() {
quantity[doc.id] = _quatity - 1;
});
}
},
),
SizedBox(width: 8),
Text(
"$_quantity",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
SizedBox(width: 8),
IconButton(
icon: Icon(Icons.add),
onPressed: (){
setState(() {
quantity[doc.id] = _quatity + 1;
});
},
),
],
),
],
),
],
),
),
)));

How to merge new field value to an existing firestore document with flutter?

I am trying to assign a delivery agent to the order of products with a dropdown containing a list of delivery agents. I am trying to get documentId and merging new field value to the documentId which already exists. But as a result, I a getting a duplicate document with the same documentId containing filed values which I want to merge. kindly help me to understand what I am doing wrong.
full code order_view.dart
import 'package:flutter/material.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import '../../services/firebase_database.dart';
import '../widgets/snack_bar.dart';
import 'client_address.dart';
import 'dashboard.dart';
import 'package:url_launcher/url_launcher.dart';
class OrderView extends StatefulWidget {
final Map<String, dynamic> orderData;
final List<String> deliveryAgent;
const OrderView(
{Key? key, required this.orderData, required this.deliveryAgent})
: super(key: key);
#override
State<OrderView> createState() => _OrderViewState();
}
class _OrderViewState extends State<OrderView> {
final FirebaseDatabase _database = FirebaseDatabase();
int index = 0;
num totalAmount = 0;
Map<String, dynamic> clientData = {};
getcountTotalAmount() async {
for (var item in widget.orderData["orders"]) {
totalAmount = totalAmount + (item["productPrice"] * item["amount"]);
}
clientData = (await _database.getClientData(widget.orderData["userId"]))!;
setState(() {});
}
#override
void initState() {
getcountTotalAmount();
super.initState();
}
#override
Widget build(BuildContext context) {
bool _isloading = true;
return Scaffold(
backgroundColor: Colors.grey[200],
appBar: AppBar(
elevation: 4,
title: const Text("Open Order"),
actions: [
TextButton(
onPressed: () async {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: const Text(
"Are you sure you want to cancel this order?",
textAlign: TextAlign.center,
),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text(
"No",
style:
TextStyle(color: Colors.green, fontSize: 16),
)),
TextButton(
onPressed: () async {
// Navigator.pop(context);
showDialog(
context: context,
builder: (context) {
return LoadingAnimationWidget.inkDrop(
color: Colors.orange,
size: 50,
);
});
await _database.removeOrder(
createTime: widget.orderData["createAt"],
);
Navigator.of(context).pop();
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (context) =>
const AdminDashboard()),
ModalRoute.withName(''),
);
ScaffoldMessenger.of(context).showSnackBar(
snackBar(
message: "Your order is removed",
color: Colors.deepOrange),
);
},
child: const Text(
"Yes",
style: TextStyle(color: Colors.red, fontSize: 16),
)),
],
);
});
},
child: const Text(
"Cancel Order",
style: TextStyle(
color: Colors.red,
fontWeight: FontWeight.w500,
fontSize: 15,
),
),
),
],
),
body: SizedBox(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: ListView(
physics: const BouncingScrollPhysics(),
children: [
Container(
color: Colors.white,
child: ListView.separated(
padding: const EdgeInsets.symmetric(vertical: 8),
shrinkWrap: true,
itemCount: widget.orderData["orders"].length,
physics: const BouncingScrollPhysics(),
itemBuilder: (context, index) {
return ListTile(
leading: Image.network(
widget.orderData["orders"][index]["productImage"],
),
title: Text(
widget.orderData["orders"][index]["productTitle"],
),
subtitle: SizedBox(
width: MediaQuery.of(context).size.width,
child: Row(
children: [
Text(
"₹ ${widget.orderData["orders"][index]["productPrice"]}",
style: const TextStyle(
color: Colors.green, fontSize: 12),
),
const Text(" - "),
Text(
widget.orderData["orders"][index]["productUnit"],
style: const TextStyle(fontSize: 12),
),
const Text(" x "),
Text(widget.orderData["orders"][index]["amount"]
.toString()),
const SizedBox(width: 5),
Text(
"Total ₹ ${widget.orderData["orders"][index]["productPrice"] * widget.orderData["orders"][index]["amount"]}",
style: const TextStyle(
color: Colors.green,
fontWeight: FontWeight.w600,
fontSize: 12,
),
),
],
),
),
);
},
separatorBuilder: (BuildContext context, int index) {
return const Divider();
},
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Delivery Slot'),
Text(
'${widget.orderData["deliverySlot"]}',
style: const TextStyle(
fontWeight: FontWeight.w500, fontSize: 16),
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
"Delivery charge: ₹${widget.orderData["taxes"]}",
),
Text(
"Total Price: ₹${totalAmount + widget.orderData["taxes"]}",
style: const TextStyle(
fontWeight: FontWeight.w500, fontSize: 16),
),
],
)
],
),
),
const SizedBox(height: 16),
Container(
width: MediaQuery.of(context).size.width,
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
decoration: const BoxDecoration(
color: Colors.white,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Ordered on: ${widget.orderData["createAt"]}',
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 14,
),
),
Text(
'Delivery at ${widget.orderData["addressType"]}',
),
const SizedBox(
height: 16,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
width: MediaQuery.of(context).size.width * 0.6,
child: Text(
'Address: ${widget.orderData["address"]}',
),
),
ElevatedButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => ClientAddress(
lat: widget.orderData["latitude"],
lag: widget.orderData["longitude"],
)));
},
child: const Text('Open location'))
],
),
],
),
),
const SizedBox(
height: 16,
),
Container(
width: MediaQuery.of(context).size.width,
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
color: Colors.white,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
"Client Details",
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 17,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
child: Text(
clientData["username"] ?? "",
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 15,
),
),
),
SizedBox(
child: Text(
clientData["contact"] ?? "",
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 15,
),
),
),
ElevatedButton.icon(
onPressed: () async {
String telephoneNumber = clientData["contact"];
Uri telephoneUrl = Uri.parse("tel:$telephoneNumber");
if (await canLaunchUrl(telephoneUrl)) {
await launchUrl(telephoneUrl);
}
},
icon: const Icon(
Icons.call,
),
label: const Text('Call'),
)
],
),
],
),
),
const SizedBox(
height: 16,
),
Container(
width: MediaQuery.of(context).size.width,
color: Colors.white,
padding: const EdgeInsets.only(bottom: 8),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
const Text(
"Delivery Agent",
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 16,
),
),
DropdownButton(
items: widget.deliveryAgent
.map(
(e) => DropdownMenuItem(
value: e,
child: Text(e),
),
)
.toList(),
onChanged: (val) {
setState(() {
index =
widget.deliveryAgent.indexOf(val.toString());
});
},
isExpanded: false,
hint: Text(
widget.deliveryAgent[index],
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 15,
),
),
),
],
),
ElevatedButton(
onPressed: () async {
bool results;
results = await _database.updateDeliveryAgent(
orderId: widget.orderData["orderId"],
deliveryAgent: widget.deliveryAgent[index].toString(),
);
if (results) {
setState(() {
_isloading = true;
});
ScaffoldMessenger.of(context).showSnackBar(
snackBar(
message: "Delivery agent assigned",
color: Colors.green,
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
snackBar(
message: "Error",
color: Colors.red,
),
);
}
setState(() {
_isloading = true;
});
},
child: const Text('Assign Agent')),
],
)),
],
),
),
);
}
}
firebase_database.dart
CollectionReference<Map<String, dynamic>> testorders =
FirebaseFirestore.instance.collection('testorders');
Future<bool> updateDeliveryAgent(
{required String orderId, required String deliveryAgent}) async {
try {
testorders.doc(orderId).set({
"deliveryAgent": {
"agentName": deliveryAgent,
"agentContact": '',
},
}, SetOptions(merge: true));
return true;
} catch (e) {
if (kDebugMode) {
print("error while assigning delivery agent: $e");
}
}
return false;
}
order.dart
Container(
width: MediaQuery.of(context).size.width,
color: Colors.white,
padding: const EdgeInsets.only(bottom: 8),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
const Text(
"Delivery Agent",
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 16,
),
),
DropdownButton(
items: widget.deliveryAgent
.map(
(e) => DropdownMenuItem(
value: e,
child: Text(e),
),
)
.toList(),
onChanged: (val) {
setState(() {
index =
widget.deliveryAgent.indexOf(val.toString());
});
},
isExpanded: false,
hint: Text(
widget.deliveryAgent[index],
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 15,
),
),
),
],
),
ElevatedButton(
onPressed: () async {
bool results;
results = await _database.updateDeliveryAgent(
orderId: widget.orderData["orderId"],
deliveryAgent: widget.deliveryAgent[index].toString(),
);
if (results) {
setState(() {
_isloading = true;
});
ScaffoldMessenger.of(context).showSnackBar(
snackBar(
message: "Delivery agent assigned",
color: Colors.green,
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
snackBar(
message: "Error",
color: Colors.red,
),
);
}
setState(() {
_isloading = true;
});
},
child: const Text('Assign Agent')),
],
)),
You cannot update a document ID once it's been defined.
See the following answer on alternative steps you can take: https://stackoverflow.com/a/52117929/9063088
There is no way you can have duplicate document IDs inside the same collection. The screenshot shows two documents sharing the same ID but for sure one of them contains one or more white spaces at the end. So there are two situations, the orderId is correct and when you call set() it adds the document with a document ID that doesn't contains white spaces, while in the database there is already one present that contains white spaces, or vice versa. When it comes to document IDs, always call .trim() so it can remove the white spaces from the beginning and from the end.
I fixed this, the main reason was firstly when I created the document with .add() where firebase auto generate the document ID, the and later while merging data in the same document ID it was creating the duplicate document ID maybe with some whitespace in it which was not visible.
But to rectify I created the data with .set() by generating the document by my own and later while merging data uses the same document ID to merge new fields in the same document ID. and finally it worked.

Flutter firebase realtime database getting user details from join request key

I am new to flutter. Seeking help with flutter and firebase real-time database. In the first image of my 'request' child, I want to retrieve all requests to a list and display the user details from the 'users' child using that list.
[request child]
[users child]:
Currently, I am using a streambuilder to get the keys but I want to show the user details under the keys. What is the best way to do that?
[Current streambuilder]
Current code
StreamBuilder<dynamic>(
stream: ref
.child('house')
.child(widget.house)
.child('request')
.child('joinReq')
.orderByChild('id')
.onValue,
builder: (context, snapshot) {
final tilesList = <Card>[];
if (snapshot.hasData) {
final joinReq = Map<String, dynamic>.from(
(snapshot.data!).snapshot.value);
joinReq.forEach((key, value) {
final nextJoinReq = Map<String, dynamic>.from(value);
nextJoinReq['key'] = key;
final joinTile = Card(
margin: const EdgeInsets.symmetric(
vertical: 5, horizontal: 7),
//elevation: 3,
color: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(5, 0, 5, 0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
nextJoinReq['id'],
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 12,
color: Colors.red,
),
),
GestureDetector(
onTap: (() {
Alert(
context: context,
//closeIcon: const Icon(Icons.close),
//title: 'LOG OUT!',
//desc: 'Do you want to log out?',
//content: const CircularProgressIndicator(),
content: Row(
children: [
const Icon(Icons.clear, size: 40),
const SizedBox(
width: 10,
),
Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
const Text(
'Delete request!',
style: TextStyle(
fontSize: 20,
color: Colors.red,
),
),
SizedBox(
width: 160,
child: Text(
'Do you want to remove \' ${nextJoinReq['id']}s \' request to join?',
textAlign: TextAlign.start,
style: const TextStyle(
fontSize: 15,
color: Colors.black,
),
),
),
],
),
],
),
style: const AlertStyle(
backgroundColor: Colors.white,
isCloseButton: false,
// isOverlayTapDismiss: false,
),
buttons: [
DialogButton(
color: Colors.black,
onPressed: () {
Navigator.pop(context);
},
child: const Text(
'No',
style: TextStyle(color: Colors.white),
),
),
DialogButton(
color: Colors.black,
onPressed: () {
Navigator.pop(context);
ref
.child('house')
.child(widget.house)
.child('request')
.child('joinReq')
.child(nextJoinReq['key'])
.remove()
.whenComplete(() => {
showSnackBar(context,
'Request deleted')
});
},
child: const Text(
'Yes',
style: TextStyle(color: Colors.white),
),
),
],
).show();
}),
child: const Icon(
Icons.clear,
size: 25.0,
color: Colors.black,
),
),
],
),
),
);
tilesList.add(joinTile);
});
}
return ListView(
children: tilesList,
);
},
)

Inserting new Widgets as List on Pressing Button in Flutter

I am making a screen like this which could select contacts from the phone book and insert the names as lists in my application. I want is that when I press Add caregiver(+) button it should select a contact and show the name.
I made a Widget for the MOM part but whenever I click the button it rewrites the MOM to any contact that I select from the phone book.
I made this screen:
I also want to add Dad and Sister's Contact in the same manner as mom, but I am unable to do it
This is my code for the screen:
import 'package:epicare/NavigBar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:contact_picker/contact_picker.dart';
//Check contacts permission
Future<PermissionStatus> _getPermission() async {
final PermissionStatus permission = await Permission.contacts.status;
if (permission != PermissionStatus.granted &&
permission != PermissionStatus.denied) {
final Map<Permission, PermissionStatus> permissionStatus =
await [Permission.contacts].request();
return permissionStatus[Permission.contacts] ??
PermissionStatus.undetermined;
} else {
return permission;
}
}
class CaregiverScreen extends StatefulWidget {
#override
_CaregiverScreenState createState() => _CaregiverScreenState();
}
class _CaregiverScreenState extends State<CaregiverScreen> {
final ContactPicker _contactPicker = new ContactPicker();
Contact _contact;
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
bool isSwitched = true;
#override
Widget build(BuildContext context) {
//Size size = MediaQuery.of(context).size;
return Scaffold(
key: _scaffoldKey,
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: const Color(0xffE5E0A1),
elevation: 0,
centerTitle: true,
title: Text(
"Add Caregiver",
style: TextStyle(
fontSize: 15.0,
color: Colors.black,
fontFamily: 'Montserrat',
fontWeight: FontWeight.normal,
),
),
leading: IconButton(
icon: Icon(
Icons.arrow_back,
color: Colors.black,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return Homepage();
},
),
);
},
),
),
body: SingleChildScrollView(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 40),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
MaterialButton(
onPressed: () async {
final PermissionStatus permissionStatus = await _getPermission();
if (permissionStatus == PermissionStatus.granted) {
//We can now access our contacts here
// var contactNumber = openContactBook();
Contact contact = await _contactPicker.selectContact();
setState(() {
_contact = contact;
});
}
else {
//If permissions have been denied show standard cupertino alert dialog
showDialog(
context: context,
builder: (BuildContext context) => CupertinoAlertDialog(
title: Text('Permissions error'),
content: Text('Please enable contacts access '
'permission in system settings'),
actions: <Widget>[
CupertinoDialogAction(
child: Text('OK'),
onPressed: () => Navigator.of(context).pop(),
)
],
));
}
},
color: const Color(0xffd4d411),
textColor: Colors.white,
child: Icon(
Icons.add,
size: 32,
),
padding: EdgeInsets.all(3),
shape: CircleBorder(),
),
Text(
'Add a Caregiver',
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 13,
color: const Color(0xff000000),
height: 1.5384615384615385,
fontWeight: FontWeight.w600),
textHeightBehavior:
TextHeightBehavior(applyHeightToFirstAscent: false),
textAlign: TextAlign.left,
)
],
),
_contact == null ? Container() : CaregiversList(_contact.fullName),
],
),
),
),
);
}
Widget CaregiversList(String name){
print(name);
var c = name.split(' ');
print(c[0]);
var caregiver = c[0];
var output = getInitials(string: caregiver, limitTo: 1);
print(output);
// var i = caregiver.codeUnitAt(0);
// print(i);
return Container(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 27),
child: Row(
//crossAxisAlignment: CrossAxisAlignment.center,
//mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
CircleAvatar(
radius: 24,
backgroundColor: const Color(0xffd4d411),
child: CircleAvatar(
radius: 22,
backgroundColor: Colors.white,
child: Text(
output,
style: TextStyle(
fontFamily: 'Segoe UI',
fontSize: 20,
color: const Color(0xff000000),
),
),
),
),
SizedBox(width: 19),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
caregiver,
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 13,
color: const Color(0xff000000),
height: 1.5384615384615385,
fontWeight: FontWeight.w600),
textHeightBehavior: TextHeightBehavior(
applyHeightToFirstAscent: false),
textAlign: TextAlign.left,
),
isSwitched
? Text(
"Activated",
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 10,
color: const Color(0x80232425),
fontWeight: FontWeight.w500),
textAlign: TextAlign.left,
)
: Text(
"Disabled",
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 10,
color: const Color(0x80232425),
fontWeight: FontWeight.w500),
textAlign: TextAlign.left,
),
],
),
SizedBox(width: 143),
FlutterSwitch(
width: 40.0,
height: 20.0,
value: isSwitched,
toggleSize: 15,
borderRadius: 40.0,
padding: 2.0,
showOnOff: false,
activeColor: const Color(0xffd4d411),
activeToggleColor: Colors.white,
inactiveColor: const Color(0xffDDDBAF),
inactiveToggleColor: Colors.white,
onToggle: (value) {
setState(() {
isSwitched = value;
print(isSwitched);
});
},
),
],
),
);
}
String getInitials({String string, int limitTo}) {
var buffer = StringBuffer();
var split = string.split(' ');
for (var i = 0 ; i < (limitTo ?? split.length); i ++) {
buffer.write(split[i][0]);
}
return buffer.toString();
}
}
Please help me out as i am new to Flutter.
Thank you in advance :)
You need to manage Caregiverlist you've selected from contacts. for example
class Caregiver {
String name;
bool isActive;
Caregiver({this.name, this.isActive});
factory Caregiver.fromJson(Map<String, dynamic> map) {
if (map == null) return null;
return Caregiver(name: map['name'] ?? "",
isActive: map['isActive']);
}
}
initialize caregiver list
List<Caregiver> _careList = [];
add Caregiver
Contact contact = await _contactPicker.selectContact();
setState(() {
_careList.add(Caregiver(name: contact, isActive: true));
});
show Caregiver list (To show ListView inside of Scrollview, add the following 3 lines.
ListView.separated(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
primary: false,
itemBuilder: (context, index) {
return _caregiverWidget(index);
},
separatorBuilder: (_, __) => Divider(),
itemCount: _careList.length);
Add new function
Widget _caregiverWidget(int index) {
Caregiver _caregiver = _careList[index];
print(_caregiver.name);
var c = _caregiver.name.split(' ');
print(c[0]);
var caregiver = c[0];
var output = getInitials(string: caregiver, limitTo: 1);
print(output);
// var i = caregiver.codeUnitAt(0);
// print(i);
return Container(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 27),
child: Row(
//crossAxisAlignment: CrossAxisAlignment.center,
//mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
CircleAvatar(
radius: 24,
backgroundColor: const Color(0xffd4d411),
child: CircleAvatar(
radius: 22,
backgroundColor: Colors.white,
child: Text(
output,
style: TextStyle(
fontFamily: 'Segoe UI',
fontSize: 20,
color: const Color(0xff000000),
),
),
),
),
SizedBox(width: 19),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
caregiver,
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 13,
color: const Color(0xff000000),
height: 1.5384615384615385,
fontWeight: FontWeight.w600),
textHeightBehavior:
TextHeightBehavior(applyHeightToFirstAscent: false),
textAlign: TextAlign.left,
),
_caregiver.isActive
? Text(
"Activated",
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 10,
color: const Color(0x80232425),
fontWeight: FontWeight.w500),
textAlign: TextAlign.left,
)
: Text(
"Disabled",
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 10,
color: const Color(0x80232425),
fontWeight: FontWeight.w500),
textAlign: TextAlign.left,
),
],
),
SizedBox(width: 143),
FlutterSwitch(
width: 40.0,
height: 20.0,
value: _caregiver.isActive,
toggleSize: 15,
borderRadius: 40.0,
padding: 2.0,
showOnOff: false,
activeColor: const Color(0xffd4d411),
activeToggleColor: Colors.white,
inactiveColor: const Color(0xffDDDBAF),
inactiveToggleColor: Colors.white,
onToggle: (value) {
setState(() {
_caregiver.isActive = value;
_careList.removeAt(index);
_careList.insert(index, _caregiver);
});
},
),
],
),
);
}

flutter show text when button is pressed

I have a row with a text saying terms of use and a button. I want to show some data but perhaps I'm not using the correct keywords. All I'm getting is how to change a text on button click.
Anyway, what should I do to let the user see the terms of use on button click?
Container(
padding: EdgeInsets.only(top: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Terms of Use",
style: TextStyle(
color: Color(0xff18172b),
fontSize: 18,
fontFamily: "Poppins",
fontWeight: FontWeight.w400,
),
),
IconButton(
iconSize: 18,
onPressed: () {},
icon: Icon(Icons.arrow_forward_ios))
],
),
),
you can navigate to another page that hold the Terms or show modal like this :
IconButton(
iconSize: 18,
onPressed: () async {
await showDialog(
barrierColor: Colors.black12.withOpacity(.6),
context: context,
builder: (_) {
return Dialog(
elevation: 0,
backgroundColor: Colors.transparent,
child: Container(
child: Text("TERMS"),
),
);
});
},
icon: Icon(Icons.arrow_forward_ios))