Flutter getX not updating UI after ading items to obs list - flutter

I'm using GetX to manage the state of my ecommerce app, and I'm stuck with the shopping cart.
I'm using Sqflite package to store carts locally.
issue: when i add a product to cart list it's not updating it automatically untill i restart the app i see the added items
Cart controller
addProductToCart(ProductModel product) async {
List<Map> items =
await _repository.getLocalByCondition('carts', 'productId', product.id);
if (items.length > 0) {
product.quantity = items.first['productQuantity'] + 1;
return await _repository.updateLocal(
'carts', 'productId', product.toMap());
}
product.quantity = 1;
return await _repository.saveLocal('carts', product.toMap());
}
#override
void onInit() {
super.onInit();
getCarts();
}
Add to cart product details
_addToCart(BuildContext context, ProductModel product) async {
int result = await _cartController.addProductToCart(product);
if (result > 0) {
Fluttertoast.showToast(msg: 'Item added to cart successfully!');
} else {
Fluttertoast.showToast(msg: 'Error to add product!');
}
}
Cart screen
Obx(() {
return Scaffold(
appBar: AppBar(
title: Text('Cart (${_cartController.cartList.length} items)',
style: TextStyle(color: Colors.black))),
bottomNavigationBar: InkWell(
onTap: () {
//_checkout(_cartController.cartList);
},
child: Container(
color: Colors.black,
height: 55,
margin: EdgeInsets.all(8),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Checkout',
style: TextStyle(color: Colors.white),
),
SizedBox(
width: 10,
),
Text(
'£' + _cartController.total.toString(),
style: TextStyle(color: Colors.white),
)
],
),
)),
body: _cartController.loading.isTrue
? Center(child: CircularProgressIndicator())
: _cartController.cartList.length > 0
? ListView.builder(
padding:
EdgeInsets.symmetric(horizontal: 8, vertical: 12),
itemBuilder: (context, index) {
return Dismissible(
key: Key(this
._cartController
.cartList[index]
.id
.toString()),
onDismissed: (val) async {
var x= await _cartController.deleteCartItem(
index, this._cartController.cartList[index].id);
if(x!>0) Fluttertoast.showToast(msg: 'deleted');
else{ Fluttertoast.showToast(msg: x.toString());
}
},
background: Container(
child: Align(
alignment: Alignment.centerRight,
child: Padding(
padding: const EdgeInsets.only(right: 28.0),
child: Icon(
Icons.delete_outline_outlined,
size: 36,
color: Colors.white,
),
)),
color: Colors.redAccent),
child: Card(
elevation: 5,
shape: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(7),
)),
child: Container(
margin: EdgeInsets.all(4),
height: 120,
child: Row(
children: [
Expanded(
flex: 3,
child: ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(5),
topRight: Radius.circular(5)),
child: Image.network(
_cartController.cartList[index].photo,
width: 150,
height: 120,
fit: BoxFit.cover,
),
),
),
Expanded(
flex: 5,
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
_cartController
.cartList[index].name,
overflow: TextOverflow.clip,
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 16),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'${_cartController.cartList[index].price - _cartController.cartList[index].discount} ' +
" x " +
_cartController
.cartList[index].quantity
.toString(),
style: TextStyle(
fontWeight: FontWeight.w500),
),
),
],
)),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
IconButton(
icon: Icon(Icons.keyboard_arrow_up),
onPressed: () {
_cartController.total.value += this
._cartController
.cartList[index]
.price -
this
._cartController
.cartList[index]
.discount;
this
._cartController
.cartList[index]
.quantity++;
},
),
Text(_cartController
.cartList[index].quantity
.toString()),
IconButton(
icon: Icon(Icons.keyboard_arrow_down),
onPressed: () {
if (_cartController
.cartList[index].quantity >
1) {
_cartController.total.value -= (this
._cartController
.cartList[index]
.price -
this
._cartController
.cartList[index]
.discount);
this
._cartController
.cartList[index]
.quantity--;
}
},
),
],
))
],
),
),
),
);
},
itemCount: _cartController.cartList.length,
)
: Center(
child: Text('Your Shopping cart is empty'),
));
});

You need to add product in _cartController.cartList.
_addToCart(BuildContext context, ProductModel product) async {
cartList.add(product);
....
}

Related

I wants to reload and update the widget in flutter when clicked on action button of snack bar

This is my code where I am showing list of pending invoices.But when i accept the it should reload the pending invoice widget after clicking on snack bar action button.When user clicks on accept button its showing snack bar and when pressed accept action button snack bar it navigate back to same widget where I needs to update that widget along with new list of pending invoices without the invoice which we have accepted
class PendingInvoiceWidget extends StatelessWidget {
final double maxWidth;
final double maxHeight;
final bool isOverdue;
final String amount;
final String savedAmount;
final String invoiceDate;
final String dueDate;
Invoice fullDetails;
int index;
bool userConsentGiven = false;
final String companyName;
PendingInvoiceWidget(
{required this.fullDetails,
required this.maxWidth,
required this.maxHeight,
required this.amount,
required this.savedAmount,
required this.index,
required this.invoiceDate,
required this.dueDate,
required this.companyName,
required this.isOverdue});
#override
Widget build(BuildContext context) {
TextEditingController acceptController = TextEditingController();
TextEditingController rejectController = TextEditingController();
List<Invoice> pendingInvoice =
Provider.of<TransactionManager>(context).pendingInvoice;
String? invoiceId = fullDetails.sId;
String invAmt = double.parse(amount).toStringAsFixed(2);
DateTime id = DateTime.parse(invoiceDate);
DateTime dd = DateTime.parse(dueDate);
DateTime currentDate = DateTime.now();
Duration dif = dd.difference(currentDate);
int daysLeft = dif.inDays;
String idueDate = DateFormat("dd-MMM-yyyy").format(dd);
String invDate = DateFormat("dd-MMM-yyyy").format(id);
double h1p = maxHeight * 0.01;
double h10p = maxHeight * 0.1;
double w10p = maxWidth * 0.1;
return ProgressHUD(child: Builder(builder: (context) {
final progress = ProgressHUD.of(context);
return ExpandableNotifier(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: w10p * .5, vertical: 10),
child: Expandable(
collapsed: ExpandableButton(
child: Card(
child: Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colours.offWhite,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
isOverdue
? Padding(
padding: EdgeInsets.symmetric(
vertical: h1p * 1),
child: Container(
// height: h1p * 4.5,
// width: w10p * 1.7,
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(5),
color: Colours.failPrimary,
),
child: const Center(
child: Padding(
padding: EdgeInsets.all(4),
child: Text(
"Overdue",
style: TextStyles.overdue,
),
),
),
),
)
: Container(),
Row(
children: [
Text(
"${fullDetails.invoiceNumber}",
style: TextStyles.textStyle6,
),
SvgPicture.asset(
"assets/images/home_images/arrow-circle-right.svg"),
],
),
expanded: Column(
children: [
ExpandableButton(
child: Card(
child: Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colours.offWhite,
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
isOverdue
? Text(
"$daysLeft days Overdue",
style: TextStyles.textStyle57,
)
: Text(
"$daysLeft days left",
style: TextStyles.textStyle57,
),
Text(
"₹ $invAmt",
style: TextStyles.textStyle58,
),
],
)
]),
),
),
),
Card(
elevation: .5,
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
height: 4,
),
const Text(
"Invoice Date",
style: TextStyles.textStyle62,
),
Text(
invDate,
style: TextStyles.textStyle63,
),
// Text(
// companyName,
// style: TextStyles.companyName,
// ),
],
),
SvgPicture.asset("assets/images/arrow.svg"),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
const SizedBox(
height: 4,
),
const Text(
"Due Date",
style: TextStyles.textStyle62,
),
Text(
idueDate,
style: TextStyles.textStyle63,
),
// Text(
// companyName,
// style: TextStyles.companyName,
// ),
],
),
],
),
),
),
Card(
child: Container(
padding: const EdgeInsets.all(10),
decoration: const BoxDecoration(),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
height: 4,
),
const Text(
"Invoice Amount",
style: TextStyles.textStyle62,
),
Text(
"₹ $invAmt",
style: TextStyles.textStyle65,
)
// Text("Asian Paints",style: TextStyles.textStyle34,),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
const SizedBox(
height: 4,
),
isOverdue
? const Text(
"Payabe Amount",
style: TextStyles.textStyle62,
)
: const Text(
"Pay Now",
style: TextStyles.textStyle62,
),
Text(
"₹ $invAmt",
style: TextStyles.textStyle66,
),
],
),
],
),
SizedBox(
height: h1p * 1.5,
),
// Row(
// mainAxisAlignment: MainAxisAlignment.start,
// children: [
// Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// isOverdue?
// const Text(
// "Interest",
// style: TextStyles.textStyle62,
// ):
// const Text(
// "You Save",
// style: TextStyles.textStyle62,
// ),
// Text(
// "₹ $savedAmount",
// style:isOverdue?
// TextStyles.textStyle73:
// TextStyles.textStyle77,
// ),
// ],
// ),
// ],
// ),
Padding(
padding: const EdgeInsets.symmetric(vertical: 10.0),
child: GestureDetector(
onTap: () {
progress!.show();
getIt<TransactionManager>()
.changeSelectedInvoice(fullDetails);
progress.dismiss();
Navigator.pushNamed(context, savemoreDetails);
},
child: Image.asset(
"assets/images/viewetails.png")),
),
Row(
children: [
Expanded(
child: InkWell(
onTap: () async {
showDialog(
context: context,
builder: (context) => Padding(
padding:
const EdgeInsets.symmetric(
// vertical: h10p * 5,
),
child: AlertDialog(
shape:
const RoundedRectangleBorder(
borderRadius:
BorderRadius.all(
Radius.circular(
10.0))),
title: Row(
children: const [
Center(
child: Text("Comment"),
),
],
),
const SizedBox(
width: 10,
),
Expanded(
child: InkWell(
onTap: () async {
showDialog(
context: context,
builder: (context) => Padding(
padding:
const EdgeInsets.symmetric(
// vertical: h10p * 4,
),
child: StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
shape:
const RoundedRectangleBorder(
borderRadius:
BorderRadius.all(
Radius.circular(
10.0))),
title: const Center(
child: Text("Consent"),
),
content: Column(
mainAxisSize:
MainAxisSize.min,
children: [
Text(
"I agree and approve Xuriti and NBFC Ditya Finance Private Limited to disburse funds to yhe seller $companyName for invoice number -${fullDetails.invoiceNumber} on my behalf"),
TextField(
controller:
acceptController,
decoration:
const InputDecoration(
hintText:
"Leave a comment *"),
onChanged: (_) {
print(acceptController
.text);
acceptController
.text.isEmpty
? Row(
children: const [
Text(
"Please write a reason",
style: TextStyle(
color:
Colors.red),
),
],
)
: Container();
},
),
SizedBox(
height: h1p * 4,
),
InkWell(
onTap: () async {
userConsentGiven =
true;
String timeStamp =
DateTime.now()
.toString();
if (acceptController
.text
.isNotEmpty) {
progress!.show();
String? message = await getIt<
TransactionManager>()
.changeInvoiceStatus(
invoiceId,
"Confirmed",
index,
fullDetails,
timeStamp,
userConsentGiven,
acceptController
.text,
"This invoice has been confirmed and Xuriti and its financing partner is authorised to disburse funds to the seller as per the invoice generated on my behalf");
progress.dismiss();
ScaffoldMessenger
.of(context)
.showSnackBar(
SnackBar(
behavior:
SnackBarBehavior
.floating,
content:
Text(
message!,
style:
const TextStyle(color: Colors.green),
)));
} else {
Fluttertoast.showToast(
msg:
"Please write a reason",
textColor:
Colors.red);
}
Navigator.pop(
context,
);
},
child: Container(
height: h1p * 8,
width: w10p * 7.5,
decoration: BoxDecoration(
borderRadius:
BorderRadius
.circular(
6),
color: Colours
.pumpkin),
child: const Center(
child: Text(
"Accept",
style: TextStyles
.subHeading,
)),
),
),
],
),
);
}),
));
},
child: Container(
height: h1p * 9,
decoration: BoxDecoration(
color: Colours.successPrimary,
borderRadius: BorderRadius.circular(5)),
child: const Center(
child: Text(
"Accept",
style: TextStyles.textStyle46,
),
),
),
),
),
],
)
],
),
),
),
],
)),
),
);
}));
}
}
Please try to use this code as SnackBar and decorate you want,
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
behavior: SnackBarBehavior.floating,
content: Text(
message!,
style: const TextStyle(color: Colors.green),
),
backgroundColor: Colors.black,
action: SnackBarAction(
label: "Reload",
onPressed: () {
setState(() {});
})));
I Hope these things are solve your issue,

create a fixed sized widget on flutter

I'm currently trying to create a row that consist of maximum 3 column widget with each of them have the property of profile picture, nickname, and status. I wanted each of them to have fixed size so that even when the nickname is long it will still take the same amount of space.
Currently I just make the column to be spaced-evenly and some of the widget still take more space than the other 2. How can I fixed this ? maybe make the nickname turned into dotted (...) when it's too long.
here's my current code:
solverWidgets.add(
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
BuildRoundedRectProfile(
height: 40,
width: 40,
name: solverTicket[solver]['nickname'],
profileLink: solverTicket[solver]['profile_picture_link'] ?? '',
),
SizedBox(height: 3),
Text(
solverTicket[solver]['nickname'],
style: weight600Style.copyWith(
color: primaryColor,
fontSize: 13,
),
),
if (solversStatus[solver] != null && (povStatus == 'pic' || povStatus == 'pic-client'))
GestureDetector(
onTap: () {
if (solversStatus[solver] == 'Done') {
setState(() {
needToLoadSolverWidgets = true;
isNotExpandedSolverWidgets[solver] = !isNotExpandedSolverWidgets[solver];
});
if (isExpandedSolverWidgetsContent[solver]) {
Future.delayed(Duration(milliseconds: 300), () {
setState(() {
needToLoadSolverWidgets = true;
isExpandedSolverWidgetsContent[solver] = false;
});
});
} else {
setState(() {
needToLoadSolverWidgets = true;
isExpandedSolverWidgetsContent[solver] = true;
});
}
}
},
child: AnimatedContainer(
duration: Duration(milliseconds: 300),
height: isNotExpandedSolverWidgets[solver] ? 20 : 55,
padding: EdgeInsets.only(top: 5, bottom: 5, left: 5, right: 5),
decoration: BoxDecoration(
color: defaultProfileColor.withOpacity(0.2),
borderRadius: BorderRadius.circular(10),
),
child: solversStatus[solver] != 'Done' ?
Text(
solversStatus[solver],
style: primaryColor600Style.copyWith(
fontSize: fontSize9,
),
).tr() : isNotExpandedSolverWidgets[solver] ?
Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
solversStatus[solver],
style: primaryColor600Style.copyWith(
fontSize: fontSize10,
),
).tr(),
Icon(
Icons.arrow_drop_down,
size: fontSize15,
),
],
) : ClipRRect(
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Row(
children: [
Text(
solversStatus[solver],
style: primaryColor600Style
.copyWith(
fontSize: fontSize9,
),
).tr(),
Icon(
Icons.arrow_drop_down,
size: fontSize18,
),
],
),
GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (BuildContext
context) =>
ReusableConfirmationDialog(
titleText: 'changeWorkStatus'.tr(),
contentText: 'rejectWorkStatus'.tr(),
confirmButtonText: 'yes'.tr(),
onConfirm: () async {
await Database.changeWorkStatus(
ticketId: widget.ticketId,
ticketData: ticketData,
targetId: solver as String,
oldWorkStatus: 'done',
workStatus: 'todo');
Navigator.pop(context);
setState(() {
isNotExpandedSolverWidgets[solver] = true;
needToLoadTicket = true;
});
}));
},
child: Container(
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
color: warningColor,
borderRadius:
BorderRadius.circular(5),
),
child: Text(
'disagree',
style: primaryColor600Style
.copyWith(
fontSize: fontSize9,
color: Colors.white,
),
).tr(),
),
)
]),
),
),
),
if(solversStatus[solver] != null && (povStatus != 'pic' && povStatus != 'pic-client'))
Container(
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
color: formBackgroundColor,
borderRadius: BorderRadius.all(
Radius.circular(10))),
child: Text(
solversStatus[solver],
style: weight600Style.copyWith(
color: primaryColor,
fontSize: 9,
),
),
),
],
),
);
use Text overflow
Text(
'You have pushed the button this many times:dfjhejh dskfjkawejfkjadshfkljhaskdfhekjnkjvnkjasdklfjjekjlkj',
maxLines: 1,
overflow: TextOverflow.ellipsis,
)
or You can use https://pub.dev/packages/marquee package, it will scroll your text infinitly. make sure to wrap this marquee widget in a sizedbox with height and width defined.

No data from sever API's is not showing on Listview using flutter

I'm fetching data from server APIs, The data is being successfully fetched from the server but the issue is that when the data is provided to Listview it cant be shown. How can I show the data on Listview in a flutter/dart?
Following is the code for fetching data from server API's
List<String> jobTitles = [];
List officeNames = [ ];
List officeLocations = [ ];
List jobTypes = [ ];
Future getJobsData() async {
var response = await http
.get(Uri.https('hospitality92.com', 'api/jobsbycategory/All'));
Map<String, dynamic> map = json.decode(response.body);
List<dynamic> jobData = map["jobs"];
if (jobTitles.length != 0) {
officeNames.clear();
jobTitles.clear();
officeLocations.clear();
jobTypes.clear();
}
for (var i = 0; i < jobData.length; i++) {
jobTitles.add(jobData[i]["title"]);
officeNames.add(jobData[i]["company_name"]);
officeLocations.add(jobData[i]["company_name"]);
jobTypes.add(jobData[i]["type"]);
}
/* print(jobTitles);
print(officeNames);
print(officeLocations);
print(jobTypes);*/
}
Here is the design code that I wanted to show:
Widget listCard(jobTitle, officeName, location, jobType, onPress) {
return Container(
child: InkWell(
onTap: onPress,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xC000000), Color(0xC000000)])),
child: ListTile(
leading: CircleAvatar(
radius: 30,
child: Image.asset(
"assets/ic_login.png",
height: 28,
width: 28,
),
),
title: Text(
jobTitle,
style: TextStyle(
fontSize: 16,
color: Colors.lightBlue,
fontFamily: 'Montserrat',
fontWeight: FontWeight.w500),
),
subtitle: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Row(
children: [
Icon(
Icons.home_outlined,
color: Colors.black,
size: 16,
),
Text(
officeName,
style: TextStyle(fontSize: 10),
),
],
),
SizedBox(
width: 10,
),
Row(
children: [
Icon(
Icons.location_pin,
color: Colors.blueGrey,
size: 16,
),
SizedBox(
width: 2,
),
Text(
location,
style: TextStyle(fontSize: 10),
),
],
),
SizedBox(
width: 10,
),
Row(
children: [
Container(
margin: const EdgeInsets.fromLTRB(0, 4, 0, 0),
decoration: BoxDecoration(
gradient: LinearGradient(colors: [
Colors.lightBlueAccent,
Colors.lightBlueAccent
])),
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Text(
jobType,
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: Colors.white),
),
),
),
],
)
//ElevatedButton(onPressed: () { }, child: Text("Full Time", style: TextStyle(fontSize: 10),),),
],
),
),
),
),
),
],
),
),
);
}
Here is the listview code
ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: jobTitle.length,
itemBuilder: (context, index) {
return listCard(jobTitles[index], officeNames[index],
officeLocations[index], jobTypes[index], () {});
}),
If I provide the static data to list it will show on listview, but dynamic data is not being shown.
Try To below Code Your problem has been solved:
Create API Call Function
Future<List<dynamic>> getJobsData() async {
String url = 'https://hospitality92.com/api/jobsbycategory/All';
var response = await http.get(Uri.parse(url), headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
});
return json.decode(response.body)['jobs'];
}
Write/Create your Widget :
Center(
child: FutureBuilder<List<dynamic>>(
future: getJobsData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
var title = snapshot.data[index]['title'];
var company = snapshot.data[index]['company_name'];
var skills = snapshot.data[index]['skills'];
var description = snapshot.data[index]['description'];
var positions = snapshot.data[index]['positions'];
return Card(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.green.shade300,
),
borderRadius: BorderRadius.circular(15.0),
),
child: ListTile(
leading: Text(skills),
title: Text(title),
subtitle: Text(
company + '\n' + description,
),
trailing: Text(positions),
),
);
},
),
);
}
return CircularProgressIndicator();
},
),
),
Your Screen Look Like

How to solve "a build function has returned null" in flutter app?

App was working perfectly before and then I had to make some changes to allow or restrict calling feature in the app based on subscription level of the user, by passing the variable value from one screen to another using provider.
one Screen 1 i am using :
Future<void> _verifyPuchase(String id) async {
PurchaseDetails purchase = _hasPurchased(id);
if (purchase != null && purchase.status == PurchaseStatus.purchased) {
print(purchase.productID);
if (Platform.isIOS) {
await _iap.completePurchase(purchase);
print('Achats antérieurs........$purchase');
isPuchased = true;
}
isPuchased = true;
checkIsPurchsed(isPurchsed: isPuchased);
} else {
isPuchased = false;
checkIsPurchsed(isPurchsed: isPuchased);
}
}
and have i have a class on screen 1:
class checkIsPurchsed with ChangeNotifier{
bool isPurchsed;
checkIsPurchsed({this.isPurchsed});
notifyListeners();
}
and on screen 5 I have:
Consumer<checkIsPurchsed>(
builder: (context,isPurchsed,child){
return isPurchsed.isPurchsed ? IconButton(
icon: Icon(Icons.call), onPressed: () => onJoin("AudioCall"),
):Center(child: Text(
'Sorry you have not subscribe the package',
),);
},
),
Consumer<checkIsPurchsed>(
builder: (context,isPurchsed,child){
return isPurchsed.isPurchsed ? IconButton(
icon: Icon(Icons.video_call), onPressed: () => onJoin("VideoCall"),
):Center(child: Text(
'Sorry you have not subscribe the package',
),);
},
),
on screen 5 when i try to open a chat this is what i am getting :
the icon buttons on which i am checking the purchase status appear when chat is opened , but after adding the above mentioned modifications the chat itself isnt opening and instead i am getting the red screen.
Update 1:
class ChatPage extends StatefulWidget {
final User sender;
final String chatId;
final User second;
ChatPage({this.sender, this.chatId, this.second});
#override
_ChatPageState createState() => _ChatPageState();
}
class _ChatPageState extends State<ChatPage> {
bool isBlocked = false;
final db = Firestore.instance;
CollectionReference chatReference;
final TextEditingController _textController = new TextEditingController();
bool _isWritting = false;
final _scaffoldKey = GlobalKey<ScaffoldState>();
//Ads _ads = new Ads();
#override
void initState() {
//_ads.myInterstitial()
//..load()
//..show();
print("object -${widget.chatId}");
super.initState();
chatReference =
db.collection("chats").document(widget.chatId).collection('messages');
checkblock();
}
var blockedBy;
checkblock() {
chatReference.document('blocked').snapshots().listen((onData) {
if (onData.data != null) {
blockedBy = onData.data['blockedBy'];
if (onData.data['isBlocked']) {
isBlocked = true;
} else {
isBlocked = false;
}
if (mounted) setState(() {});
}
// print(onData.data['blockedBy']);
});
}
List<Widget> generateSenderLayout(DocumentSnapshot documentSnapshot) {
return <Widget>[
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Container(
child: documentSnapshot.data['image_url'] != ''
? InkWell(
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
new Container(
margin: EdgeInsets.only(
top: 2.0, bottom: 2.0, right: 15),
child: Stack(
children: <Widget>[
CachedNetworkImage(
placeholder: (context, url) => Center(
child: CupertinoActivityIndicator(
radius: 10,
),
),
errorWidget: (context, url, error) =>
Icon(Icons.error),
height:
MediaQuery.of(context).size.height * .65,
width: MediaQuery.of(context).size.width * .9,
imageUrl:
documentSnapshot.data['image_url'] ?? '',
fit: BoxFit.fitWidth,
),
Container(
alignment: Alignment.bottomRight,
child:
documentSnapshot.data['isRead'] == false
? Icon(
Icons.done,
color: secondryColor,
size: 15,
)
: Icon(
Icons.done_all,
color: primaryColor,
size: 15,
),
)
],
),
height: 150,
width: 150.0,
color: secondryColor.withOpacity(.5),
padding: EdgeInsets.all(5),
),
Padding(
padding: const EdgeInsets.only(right: 10),
child: Text(
documentSnapshot.data["time"] != null
? DateFormat.yMMMd()
.add_jm()
.format(documentSnapshot.data["time"]
.toDate())
.toString()
: "",
style: TextStyle(
color: secondryColor,
fontSize: 13.0,
fontWeight: FontWeight.w600,
)),
)
],
),
onTap: () {
Navigator.of(context).push(
CupertinoPageRoute(
builder: (context) => LargeImage(
documentSnapshot.data['image_url'],
),
),
);
},
)
: Container(
padding: EdgeInsets.symmetric(
horizontal: 15.0, vertical: 10.0),
width: MediaQuery.of(context).size.width * 0.65,
margin: EdgeInsets.only(
top: 8.0, bottom: 8.0, left: 80.0, right: 10),
decoration: BoxDecoration(
color: primaryColor.withOpacity(.1),
borderRadius: BorderRadius.circular(20)),
child: Column(
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Container(
child: Text(
documentSnapshot.data['text'],
style: TextStyle(
color: Colors.black87,
fontSize: 16.0,
fontWeight: FontWeight.w600,
),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Text(
documentSnapshot.data["time"] != null
? DateFormat.MMMd()
.add_jm()
.format(documentSnapshot
.data["time"]
.toDate())
.toString()
: "",
style: TextStyle(
color: secondryColor,
fontSize: 13.0,
fontWeight: FontWeight.w600,
),
),
SizedBox(
width: 5,
),
documentSnapshot.data['isRead'] == false
? Icon(
Icons.done,
color: secondryColor,
size: 15,
)
: Icon(
Icons.done_all,
color: primaryColor,
size: 15,
)
],
),
],
),
],
)),
),
],
),
),
];
}
_messagesIsRead(documentSnapshot) {
return <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
InkWell(
child: CircleAvatar(
backgroundColor: secondryColor,
radius: 25.0,
child: ClipRRect(
borderRadius: BorderRadius.circular(90),
child: CachedNetworkImage(
imageUrl: widget.second.imageUrl[0] ?? '',
useOldImageOnUrlChange: true,
placeholder: (context, url) => CupertinoActivityIndicator(
radius: 15,
),
errorWidget: (context, url, error) => Icon(Icons.error),
),
),
),
onTap: () => showDialog(
barrierDismissible: false,
context: context,
builder: (context) {
return Info(widget.second, widget.sender, null);
}),
),
],
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
child: documentSnapshot.data['image_url'] != ''
? InkWell(
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
new Container(
margin: EdgeInsets.only(
top: 2.0, bottom: 2.0, right: 15),
child: CachedNetworkImage(
placeholder: (context, url) => Center(
child: CupertinoActivityIndicator(
radius: 10,
),
),
errorWidget: (context, url, error) =>
Icon(Icons.error),
height: MediaQuery.of(context).size.height * .65,
width: MediaQuery.of(context).size.width * .9,
imageUrl:
documentSnapshot.data['image_url'] ?? '',
fit: BoxFit.fitWidth,
),
height: 150,
width: 150.0,
color: Color.fromRGBO(0, 0, 0, 0.2),
padding: EdgeInsets.all(5),
),
Padding(
padding: const EdgeInsets.only(right: 10),
child: Text(
documentSnapshot.data["time"] != null
? DateFormat.yMMMd()
.add_jm()
.format(documentSnapshot.data["time"]
.toDate())
.toString()
: "",
style: TextStyle(
color: secondryColor,
fontSize: 13.0,
fontWeight: FontWeight.w600,
)),
)
],
),
onTap: () {
Navigator.of(context).push(CupertinoPageRoute(
builder: (context) => LargeImage(
documentSnapshot.data['image_url'],
),
));
},
)
: Container(
padding: EdgeInsets.symmetric(
horizontal: 15.0, vertical: 10.0),
width: MediaQuery.of(context).size.width * 0.65,
margin: EdgeInsets.only(top: 8.0, bottom: 8.0, right: 10),
decoration: BoxDecoration(
color: secondryColor.withOpacity(.3),
borderRadius: BorderRadius.circular(20)),
child: Column(
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Container(
child: Text(
documentSnapshot.data['text'],
style: TextStyle(
color: Colors.black87,
fontSize: 16.0,
fontWeight: FontWeight.w600,
),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Text(
documentSnapshot.data["time"] != null
? DateFormat.MMMd()
.add_jm()
.format(documentSnapshot
.data["time"]
.toDate())
.toString()
: "",
style: TextStyle(
color: secondryColor,
fontSize: 13.0,
fontWeight: FontWeight.w600,
),
),
],
),
],
),
],
)),
),
],
),
),
];
}
List<Widget> generateReceiverLayout(DocumentSnapshot documentSnapshot) {
if (!documentSnapshot.data['isRead']) {
chatReference.document(documentSnapshot.documentID).updateData({
'isRead': true,
});
return _messagesIsRead(documentSnapshot);
}
return _messagesIsRead(documentSnapshot);
}
generateMessages(AsyncSnapshot<QuerySnapshot> snapshot) {
return snapshot.data.documents
.map<Widget>((doc) => Container(
margin: const EdgeInsets.symmetric(vertical: 10.0),
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: doc.data['type'] == "Call"
? [
Text(doc.data["time"] != null
? "${doc.data['text']} : " +
DateFormat.yMMMd()
.add_jm()
.format(doc.data["time"].toDate())
.toString() +
" by ${doc.data['sender_id'] == widget.sender.id ? "You" : "${widget.second.name}"}"
: "")
]
: doc.data['sender_id'] != widget.sender.id
? generateReceiverLayout(
doc,
)
: generateSenderLayout(doc)),
))
.toList();
}
#override
Widget build(BuildContext context) {
ChangeNotifierProvider<checkIsPurchsed>(
create: (context)=>checkblock(),
child: Scaffold(
key: _scaffoldKey,
backgroundColor: Colors.white,
appBar: AppBar(
centerTitle: true,
elevation: 0,
title: Text(widget.second.name),
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
color: Colors.white,
onPressed: () => Navigator.pop(context),
),
actions: <Widget>[
Consumer<checkIsPurchsed>(
builder: (context,isPurchsed,child){
return isPurchsed.isPurchsed ? IconButton(
icon: Icon(Icons.call), onPressed: () => onJoin("AudioCall"),
):Center(child: Text(
'Sorry you have not subscribe the package',
),);
},
),
Consumer<checkIsPurchsed>(
builder: (context,isPurchsed,child){
return isPurchsed.isPurchsed ? IconButton(
icon: Icon(Icons.video_call), onPressed: () => onJoin("VideoCall"),
):Center(child: Text(
'Sorry you have not subscribe the package',
),);
},
),
}
The problematic area is:
#override
Widget build(BuildContext context) {
ChangeNotifierProvider<checkIsPurchsed>(
There's no return in front of ChangeNotifierProvider, so it doesn't return a Widget. Correct would be:
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider<checkIsPurchsed>(

List.Builder giving range error in Flutter

I have added my entire code over here. The getRecords method takes more time to add to the lists and hence my list returns empty at first and so listbuilder fails giving range error and that only range accepted is 0. BTW, Its a Todo app.
InitState :
void initState() {
super.initState();
setState(() {
getRecords();
});
}
Getting from the database
void getRecordsAndDisplay() async {
final records = await Firestore.instance.collection('tasks').getDocuments();
for (var record in records.documents) {
if (record.data['phone'] == '1') {
int len = record.data['task'].length;
if (len != null || len != 0) {
for (int i = 0; i < len; i++) {
String temp = record.data['task'][i];
tasks.add(temp);
}
}
else
continue;
}
else
continue;
}
setState(() {
listView = ListView.builder(
scrollDirection: Axis.vertical,
itemCount: tasks.length,
itemBuilder: (BuildContext context,int index) {
return Container(
margin: EdgeInsets.only(bottom: 10.0),
decoration: BoxDecoration(
color: Colors.deepPurple[700],
borderRadius: BorderRadius.all(Radius.circular(20.0)),
),
child: ListTile(
onTap: (){},
leading: IconButton(
icon: Icon(Icons.delete),
iconSize: 25.0,
color: Colors.white,
onPressed: () {
setState(() {
tasks.removeAt(index);
checkValue.removeAt(index);
updateValue();
});
},
),
title: Text(
'${tasks[index]}',
style: TextStyle(
fontSize: 18.0,
color: Colors.white,
fontWeight: FontWeight.bold,
decoration: checkValue[index]
? TextDecoration.lineThrough
: null,
),
),
trailing: Checkbox(
value: checkValue[index],
activeColor: Colors.white,
checkColor: Colors.deepPurple[700],
onChanged: (bool value) {
setState(() {
checkValue[index] = !checkValue[index];
});
},
),
),
);
},
);
});
}
Scaffold:
return Scaffold(
backgroundColor: Color(0xff8780FF),
body: SafeArea(
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
colors: [Colors.deepPurple[400], Color(0xff6B63FF)])),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(30.0, 30.0, 30.0, 15.0),
decoration: BoxDecoration(boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.2),
spreadRadius: 1.0,
blurRadius: 50.0,
),
]),
child: Icon(
Icons.list,
color: Colors.white,
size: 30.0,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
padding: EdgeInsets.only(
bottom: 20.0,
left: 30.0,
),
child: Text(
'Todo List',
style: TextStyle(
color: Colors.white,
fontSize: 35.0,
fontWeight: FontWeight.w900,
),
),
),
Expanded(
child: SizedBox(
width: 20.0,
),
),
IconButton(
padding: EdgeInsets.only(
right: 10.0,
bottom: 20.0,
),
icon: Icon(Icons.add),
iconSize: 30.0,
color: Colors.white,
onPressed: () async {
final resultText = await showModalBottomSheet(
context: context,
builder: (context) => AddTaskScreen(),
isScrollControlled: true);
setState(() {
tasks.add(resultText);
checkValue.add(false);
Firestore.instance
.collection('tasks')
.document('1')
.updateData({
'task': FieldValue.arrayUnion([resultText]),
});
});
},
),
IconButton(
padding: EdgeInsets.only(
right: 10.0,
bottom: 20.0,
),
icon: Icon(Icons.delete_outline),
iconSize: 30.0,
color: Colors.white,
onPressed: () {
setState(() {
tasks.clear();
checkValue.clear();
Firestore.instance
.collection('tasks')
.document('1')
.updateData({
'task': null,
});
});
},
),
],
),
],
),
Flexible(
child: Container(
padding: EdgeInsets.only(left: 10.0, right: 10.0),
height: MediaQuery.of(context).size.height,
child: listView,
),
),
],
),
),
),
);
Please help me out. I am stuck with this for a long time :(
the problem is that in initstate you cannot await for async methods so you should implement a StreamBuilder that wraps your listview..
A streambuilder is a widget that takes a stream and waits for the call completition then when the data is ok shows a widget -> your listview
A little example
StreamBuilder(
stream: YOUR_ASYNC_CALL_THAT_RETURN_A_STREAM,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Container(
alignment: Alignment.center,
child: Text(
"NO ITEMS"
),
);
}
else {
var yourList = snapshot.data.documents;//there you have to do your implementation
return ListView.builder(
itemBuilder: (context, index) => buildItem(index,yourList[index]),
itemCount: yourList.length,
);
}
},
),