I am developing a cart page which contains + and - buttons, on pressing it , the value in the backend changes, but it doesn't automatically change in the frontend.
Cartpage.dart
class CartUI extends StatefulWidget {
const CartUI({Key? key}) : super(key: key);
#override
State<CartUI> createState() => _CartUIState();
}
class _CartUIState extends State<CartUI> {
#override
Widget build(BuildContext context) {
final user = Provider.of<Userr?>(context, listen: false);
return Scaffold(
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Column(children: [
Padding(
padding: const EdgeInsets.only(top: 10.0),
child: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('myOrders')
.doc(user?.uid)
.collection('items')
.snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Lottie.asset('assets/animations/delivery.json'),
);
} else {
return ListView.builder(
physics: NeverScrollableScrollPhysics(),
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: snapshot.data!.docs.length,
itemBuilder: (BuildContext context, int index) {
final DocumentSnapshot documentSnapshot =
snapshot.data!.docs[index];
return Container(
height: 120,
width: 300,
child: Row(
children: [
Column(
children: [
SizedBox(
width: 200,
child: Text(
documentSnapshot['name'],
style: const TextStyle(
color: Colors.black87,
fontWeight: FontWeight.bold,
fontSize: 15,
),
),
),
Text(
documentSnapshot['quantity'].toString(),
style: const TextStyle(
fontSize: 15,
),
),
Text(
'Rs.${documentSnapshot['price'].toString()}',
style: const TextStyle(
color: Colors.black87,
fontSize: 15,
),
),
Row(
mainAxisAlignment:
MainAxisAlignment.start,
children: [
const SizedBox(
width: 40,
),
ElevatedButton(
onPressed: () {
if (documentSnapshot['value'] != 0.0) {
setState(() {
String id = documentSnapshot['docid'];
final user = Provider.of<Userr?>(context, listen: false);
var postDocRef = FirebaseFirestore.instance.collection('myOrders').doc(user?.uid).collection('items').doc();
Provider.of<Calculations>(context, listen: false).updatecartdata(
context,
{
'value': documentSnapshot['value'] - 0.5,
'price': documentSnapshot['price'] - (documentSnapshot['ogprice'] / 2),
},id
);
}
);
}
if (documentSnapshot['value'] ==
0.5) {
String id =
documentSnapshot['docid'];
Provider.of<ManageData>(
context,
listen: false)
.deleteData(context, id);
}
},
child: const Text('-'),
),
const SizedBox(width: 20),
Text(documentSnapshot['value']
.toString()),
const SizedBox(width: 20),
ElevatedButton(
onPressed: () {
String id =
documentSnapshot['docid'];
final user =
Provider.of<Userr?>(context,
listen: false);
var postDocRef =
FirebaseFirestore.instance
.collection('myOrders')
.doc(user?.uid)
.collection('items')
.doc();
Provider.of<Calculations>(context, listen: false).updatecartdata(
context,
{
'value': documentSnapshot['value'] + 0.5,
'price': documentSnapshot['price'] + (documentSnapshot['ogprice'] / 2),
},id
);
},
child: const Text('+'),
),
]),
],
),
],
),
);
});
}
},
),
),
_BillDetailView(),
]),
],
),
),
);
}
}
class _BillDetailView extends StatelessWidget {
#override
Widget build(BuildContext context) {
final textStyle =
Theme
.of(context)
.textTheme
.bodyText1!
.copyWith(fontSize: 16.0);
return Container(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Bill Details',
style:
Theme
.of(context)
.textTheme
.headline6!
.copyWith(fontSize: 17.0),
),
SizedBox(
height: 5,
),
FutureBuilder(
future: Provider.of<Calculations>(context, listen: false)
.getTotalCost(context),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Item total', style: textStyle),
Text('${snapshot.data}', style: textStyle),
],
);
} else if (snapshot.hasError) {
return Text("Error: ${snapshot.error.toString()}");
} else {
return const CircularProgressIndicator();
}
},
),
],
),
);
}
}
Calculation.dart
Future<dynamic> getTotalCost(BuildContext context) async {
final user = Provider.of<Userr?>(context, listen: false);
double totalCost = 0.0;
QuerySnapshot snapshot = await FirebaseFirestore.instance
.collection('myOrders')
.doc(user?.uid)
.collection('items')
.get();
for (var doc in snapshot.docs) {
totalCost += doc["price"];
}
print(totalCost.toString());
return totalCost.toString();
}
The value in the front end changes but last updated(Added or subtracted) value is not reflecting.After hot reload it changes, but not automatically.
How to change this code to automatically update the item total in the front end.
You need to use StreamBuilder instead of FutureBuilder to get live updates.
Changes your Calculation.dart to:
Stream<dynamic> getTotalCost(BuildContext context) async {
final user = Provider.of<Userr?>(context, listen: false);
double totalCost = 0.0;
QuerySnapshot snapshot = await FirebaseFirestore.instance
.collection('myOrders')
.doc(user?.uid)
.collection('items')
.snapshots();
for (var doc in snapshot.docs) {
totalCost += doc["price"];
}
print(totalCost.toString());
return totalCost.toString();
}
And change FutureBuilder to StreamBuilder:
StreamBuilder(
stream: Provider.of<Calculations>(context, listen: false)
.getTotalCost(context),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Item total', style: textStyle),
Text('${snapshot.data}', style: textStyle),
],
);
} else if (snapshot.hasError) {
return Text("Error: ${snapshot.error.toString()}");
} else {
return const CircularProgressIndicator();
}
},
),
Related
My app reads data from PostgreSQL and displays on the screen in a listview. While selecting an item from listview app is getting refreshed and items are appending to existing list. My intention is to read data only once from the DB, display in list view, select single/multiple and proceed with processing. Any suggestions would be appriciated.
import 'package:e2/Models/MasterPositions.dart';
import 'package:flutter/material.dart';
import 'package:e2/Models/model_positions.dart';
class MasterControl extends StatefulWidget {
const MasterControl({super.key});
#override
State<MasterControl> createState() => _MasterControlState();
}
class _MasterControlState extends State<MasterControl> {
List<MasterPositions> selectedContacts = [];
List<MasterPositions> fetchedPositions = [];
List<MasterPositions> positions = [];
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Master Control"),
centerTitle: true,
automaticallyImplyLeading: false,
),
body: SafeArea(
child: Column(
children: [
Expanded(
child: FutureBuilder<List<dynamic>>(
future: ModelsPositions().fetchPositionsData(),
builder: (context, snapshot) {
List<dynamic> positionsRaw = snapshot.data ?? [];
for (var pos in positionsRaw) {
positions.add(MasterPositions(
custID: pos[0],
custName: pos[1],
mtm: double.tryParse(pos[2]) ?? 0.0,
availableCash: double.tryParse(pos[3]) ?? 0.0,
));
}
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const Center(child: CircularProgressIndicator());
default:
if (snapshot.hasError) {
return const Center(
child: Text(
'Error while loading Master Positions screen'));
} else {
return buildPositions(positions);
}
}
},
)),
],
),
),
);
}
Widget buildPositions(List<dynamic> positions) {
return ListView.builder(
physics: BouncingScrollPhysics(),
itemCount: positions.length,
itemBuilder: (context, index) {
final pos = positions[index];
final custID = pos.custID;
final custName = pos.custName;
final mtm = pos.mtm;
final availableCash = pos.availableCash;
final isSelected = pos.isSelected;
return ListTile(
horizontalTitleGap: -5,
title: Card(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(custID),
const SizedBox(height: 5),
Text(custName)
],
),
),
Flexible(
fit: FlexFit.tight,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('MTM : $mtm',
softWrap: false,
style: const TextStyle(fontFamily: 'Roboto')),
const SizedBox(height: 10),
Text(
'Available : $availableCash',
softWrap: false,
),
const SizedBox(
height: 10,
),
],
),
),
],
),
),
leading: isSelected
? Icon(
Icons.check_circle,
color: Colors.green[700],
)
: const Icon(
Icons.check_circle_outline,
color: Colors.grey,
),
onTap: () {
setState(() {
positions[index].isSelected = !positions[index].isSelected;
if (positions[index].isSelected == true) {
selectedContacts.add(MasterPositions(
custID: custID,
custName: custName,
mtm: mtm,
availableCash: availableCash));
} else if (positions[index].isSelected == false) {
selectedContacts.removeWhere(
(element) => element.custID == positions[index].custID);
}
});
},
);
});
}
}
I often use something like this:
if (snapshot.hasData) {
if (snapshot.data!.isNotEmpty) {
List<dynamic> positionsRaw = snapshot.data ?? [];
for (var pos in positionsRaw) {
positions.add(MasterPositions(
custID: pos[0],
custName: pos[1],
mtm: double.tryParse(pos[2]) ?? 0.0,
availableCash: double.tryParse(pos[3]) ?? 0.0,
));
return buildPositions(positions);
} else {
// return something
}
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
And so you can guarantee that your widget will be built with data, and only be rebuilt when your new data it's loaded
I have been working on the chat functionality of an app. However, I have found that the message is been saved on the backend but does not display on the screen. Any help will be beneficial. I would like to know where I went wrong and see if the chat functionality can function properly. I would like for the sender of the text message to see the message and have the ability to communicate with the receiver of the message seemlessly. Below is the code snippet:
class MessageCenter extends StatefulWidget {
final String garageUid;
final String garageName;
const MessageCenter(
{super.key, required this.garageUid, required this.garageName});
#override
State<MessageCenter> createState() =>
_MessageCenterState(garageName, garageUid);
}
class _MessageCenterState extends State<MessageCenter> {
CollectionReference chats = FirebaseFirestore.instance.collection('chats');
final String garageUid;
final String garageName;
final currentUserId = FirebaseAuth.instance.currentUser!.uid;
var chatDocId;
final _textController = TextEditingController();
_MessageCenterState(this.garageUid, this.garageName);
#override
void initState() {
chats
.where('users', isEqualTo: {garageUid: null, currentUserId: null})
.limit(1)
.get()
.then(
(QuerySnapshot querySnapshot) {
if (querySnapshot.docs.isNotEmpty) {
chatDocId = querySnapshot.docs.single.id;
} else {
chats.add({
'users': {currentUserId: null, garageUid: null}
}).then((value) => {chatDocId = value});
}
},
)
.catchError((error) {});
super.initState();
}
void sendMessage(String msg) {
if (msg == '') return;
chats.doc(chatDocId).collection('messages').add({
'createdOn': FieldValue.serverTimestamp(),
'uid': currentUserId,
'msg': msg
}).then((value) {
_textController.text = '';
});
}
bool isSender(String user) {
return user == currentUserId;
}
Alignment getAlignment(user) {
if (user == currentUserId) {
return Alignment.topRight;
}
return Alignment.topLeft;
}
#override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('chats')
.doc(chatDocId)
.collection('messages')
.orderBy('createdOn', descending: true)
.snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return const Center(
child: Text('Something went wrong'),
);
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
if (snapshot.hasData) {
var data;
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
previousPageTitle: "back",
middle: Text(garageUid),
trailing: CupertinoButton(
child: const Icon(CupertinoIcons.phone),
onPressed: () {},
),
),
child: SafeArea(
child: Column(
children: [
Expanded(
child: ListView(
reverse: true,
children:
snapshot.data!.docs.map((DocumentSnapshot document) {
data = document.data()!;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: ChatBubble(
clipper: ChatBubbleClipper6(
nipSize: 0,
radius: 0,
type: isSender(data['uid'].toString())
? BubbleType.sendBubble
: BubbleType.receiverBubble,
),
alignment: getAlignment(data['uid'].toString()),
margin: const EdgeInsets.only(top: 20),
backGroundColor: isSender(data['uid'].toString())
? const Color(0xFF08C187)
: const Color(0xffE7E7ED),
child: Container(
constraints: BoxConstraints(
maxWidth:
MediaQuery.of(context).size.width * 0.7,
),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
data['msg'],
style: TextStyle(
color:
isSender(data['uid'].toString())
? Colors.white
: Colors.black),
maxLines: 100,
overflow: TextOverflow.ellipsis,
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
data['createdOn'] == null
? DateTime.now().toString()
: data['createdOn']
.toDate()
.toString(),
style: TextStyle(
fontSize: 10,
color:
isSender(data['uid'].toString())
? Colors.white
: Colors.black),
),
],
),
],
),
),
),
);
}).toList(),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Expanded(
child: CupertinoTextField(
controller: _textController,
)),
CupertinoButton(
child: const Icon(Icons.send_sharp),
onPressed: () => sendMessage(_textController.text))
],
),
],
),
),
);
}
return Container();
},
);
}
}
I want to download a list from firestore and display as a list in flutter widget. The data is successfully downloaded (proved by the print(cp.data()).
However, the result shown is [Instance of '_JsonQueryDocumentSnapshot'] instead of the actual carpark data.
Could anyone pls help point out what the bug is.
Thanks
class DownloadDataScreen extends StatefulWidget {
#override
_DownloadDataScreen createState() => _DownloadDataScreen();
}
class _DownloadDataScreen extends State<DownloadDataScreen> {
List<DocumentSnapshot> carparkList = []; //List for storing carparks
void initState() {
super.initState();
readFromFirebase();
}
Future readFromFirebase() async {
// await FirebaseFirestore.instance
await FirebaseFirestore.instance
.collection('carpark')
.get()
.then((QuerySnapshot snapshot) {
snapshot.docs.forEach(
(DocumentSnapshot cp) {
carparkList.add(cp);
print('printing cp');
print(cp.data());
},
);
});
**return carparkList;**
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text(
'Car Park',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: FutureBuilder(
future: readFromFirebase(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
List<Widget> children;
if (snapshot.hasData) {
children = <Widget>[
const Icon(
Icons.check_circle_outline,
color: Colors.green,
size: 60,
),
Padding(
padding: const EdgeInsets.only(top: 16),
child: Column(
children: [
Text('Result: ${snapshot.data}'),
],
),
)
];
} else if (snapshot.hasError) {
children = <Widget>[
const Icon(
Icons.error_outline,
color: Colors.red,
size: 60,
),
Padding(
padding: const EdgeInsets.only(top: 16),
child: Text('Error: ${snapshot.error}'),
)
];
} else {
children = const <Widget>[
SizedBox(
child: CircularProgressIndicator(),
width: 60,
height: 60,
),
Padding(
padding: EdgeInsets.only(top: 16),
child: Text('Awaiting result...'),
)
];
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: children,
),
);
},
),
);
}
}
First, you don't need to call the function from the init because you already use the FutureBuilder.
Also, you don't need to cast it because when the future completes, the async snapshot already would provide you a list of DocumentSnapshot in the data and the .doc propertie.
Like this:
FutureBuilder<QuerySnapshot>(
builder:(context,snapshot){
if(snapshot.hasData){
/// here your data
snapshot.data.docs;
}
)
I've been trying to check if user selected data matches with my firestore data.
onPressed: () async{
await Navigator.of(context).push(MaterialPageRoute(builder: (context) => Checker (
from: fromSel,
to: toSel,
)));
},
and in the second page i used
StreamBuilder(
stream: Firestore.instance
.collection('Schedules')
.where('from', isEqualTo: from)
.where('to', isEqualTo: to)
.snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
if (!snapshot.hasData)
return Center(child: CircularProgressIndicator());
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index){
DocumentSnapshot power = snapshot.data.documents[index];
print(power['from']);
print(power['to']);
return Container(
height: 200,
width: MediaQuery.of(context).size.width,
child: Column(
children: [
Text(power['from']),
Text(power['to'])
],
),
);
}
);
}),
so the problem i'm getting is it's not displaying the value when i use .where('from', isEqualTo: from) but it works when i use .where('from', isEqualTo: 'Adama'). and also works with .where('from', isEqualTo: from) when i instantiate from value manually like String from = 'Adama'
can you please tell me what the problem is?
and below is my firestore structure
below is the whole code for the checker (renamed to search)
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:demo/BookingPages/budget.dart';
import 'package:demo/Lists/trip.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Search extends StatefulWidget {
final from, to, seat, adult, child, infant;
final DateTime arrive, depart;
Search(
{Key key, this.from, this.to, this.seat, this.arrive, this.depart, this.adult, this.infant, this.child})
: super(key: key);
#override
_SearchState createState() => _SearchState(from: from, to: to, seat: seat, adult: adult, child: child, infant: infant, arrive: arrive, depart: depart);
}
class _SearchState extends State<Search> {
// Stream<QuerySnapshot> comparision;
var from, to, seat, adult, child, infant;
final DateTime arrive, depart;
_SearchState(
{Key key, this.from, this.to, this.seat, this.arrive, this.depart, this.adult, this.infant, this.child});
Stream<QuerySnapshot> comparision(BuildContext context) async* {
try{
yield* Firestore.instance
.collection('Schedules')
.where('from', isEqualTo: from.toString())
.where('to', isEqualTo: to.toString())
// .where('dates', arrayContains: widget.depart.day)
.snapshots();
}catch(e){
print(e);
}
}
// #override
// void initState() {
// // TODO: implement initState
// comparision = Firestore.instance
// .collection('Schedules')
// .where('from', isEqualTo: from)
// .where('to', isEqualTo: to)
// .snapshots();
//
// super.initState();
// }
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Expanded(
child: StreamBuilder(
stream: Firestore.instance
.collection('Schedules')
.where('from', isEqualTo: from)
.where('to', isEqualTo: to)
.snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
if (!snapshot.hasData)
return Center(child: CircularProgressIndicator());
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index){
DocumentSnapshot power = snapshot.data.documents[index];
print(power['from']);
print(power['to']);
return Container(
height: 200,
width: MediaQuery.of(context).size.width,
child: Column(
children: [
Text(power['from']),
Text(power['to'])
],
),
);
}
);
}),
)
// Expanded(
// child: StreamBuilder<QuerySnapshot>(
// stream: comparision,
// builder: (BuildContext context, AsyncSnapshot<QuerySnapshot>snapshot) {
// if (!snapshot.hasData)
// return Center(child: CircularProgressIndicator());
// return ListView.builder(
// itemCount: snapshot.data.documents.length,
// itemBuilder: (context, index){
// DocumentSnapshot power = snapshot.data.documents[index];
// print(power['from']);
// print(power['to']);
// return Container(
// height: 200,
// width: MediaQuery.of(context).size.width,
// child: Column(
// children: [
// Text(power['from']),
// Text(power['to'])
// ],
// ),
// );
// }
// );
// },
// ),
// ),
],
)
);
}
}
class TripCard extends StatefulWidget {
#override
_TripCardState createState() => _TripCardState();
}
class _TripCardState extends State<TripCard> {
#override
Widget build(BuildContext context) {
return Container();
}
}
below is my first page code which includes the values
import 'package:flutter/material.dart';
import 'search.dart';
class Other extends StatefulWidget {
#override
_OtherState createState() => _OtherState();
}
class _OtherState extends State<Other> {
var from = [
'Addis Ababa', 'Adama', 'Dire Dawa', 'Ali Sabieh', 'Djibouti'
];
var fromSel = 'Addis Ababa';
var to = [
'Addis Ababa', 'Adama', 'Dire Dawa', 'Ali Sabieh', 'Djibouti'
];
var toSel = 'Djibouti';
#override
Widget build(BuildContext context) {
return Container(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
child: Container(
//height: 203,
child: Column(
children: [
SizedBox(height: 15,),
Container(
//decoration: BoxDecoration(border: Border.all(color: Colors.grey)),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
width: MediaQuery.of(context).size.width/2-19,
height: 60,
padding: EdgeInsets.symmetric(horizontal: 15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('From', style: TextStyle(
fontSize: 18,
color: Colors.grey
),),
SizedBox(height: 0,),
Expanded(
child: DropdownButton<String>(
underline: Container(color: Colors.transparent),
items: from.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value, style: TextStyle(
fontSize: 18
),),
);
}).toList(),
isExpanded: true,
isDense: false,
elevation: 5,
hint: Text('From'),
value: fromSel,
onChanged: (String newValue){
setState(() {
this.fromSel = newValue;
});
}),
),
],
),
),
Container(height: 50, child: VerticalDivider(color: Colors.grey)),
Container(
width: MediaQuery.of(context).size.width/2-19,
height: 60,
padding: EdgeInsets.symmetric(horizontal: 15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('To', style: TextStyle(
fontSize: 18,
color: Colors.grey
),),
SizedBox(height: 0,),
Expanded(
child: DropdownButton<String>(
underline: Container(color: Colors.transparent),
items: to.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value, style: TextStyle(
fontSize: 18
),),
);
}).toList(),
isExpanded: true,
isDense: false,
elevation: 5,
hint: Text('to'),
value: toSel,
onChanged: (String newValue){
setState(() {
this.toSel = newValue;
});
}),
),
],
),
),
],
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
child: MaterialButton(
onPressed: () async{
await Navigator.of(context).push(MaterialPageRoute(builder: (context) => Search (
from: fromSel,
to: toSel,
depart: _startDate,
arrive: _endDate,
seat: _options[_selectedIndex],
adult: adultSel.toString(),
child: childSel.toString(),
infant: infantSel.toString(),
)));
},
minWidth: MediaQuery
.of(context)
.size
.width - 80,
height: 45,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
color: Colors.lightGreen,
splashColor: Colors.green,
child: Text(
"Search",
style: TextStyle(color: Colors.white, fontSize: 18),
),
),
)
],
),
),
),
);
}
}
I have added a GIF where you can see that when I click on favourite (heart) menu it loads smoothly and doesn't flick but when I click on side menu it flicks
I am working on an app and I am trying to resolve an issue, there is a screen whenever I click it, it flicks or blinks, it kind of refreshes. All the content it contain refresh, like if I click it I feel like I come on that screen then the items come there later on, it happens in few frictions of seconds but it is too annoying. I tried everything but still.
I tried to slow down the animation globally by using time dilation but it is still happening.
const String logo = "assets/profile/images/stadia_logo.svg";
class ProfileScreen extends StatefulWidget {
#override
_ProfileScreenState createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
#override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
final StorageService ref = StorageService();
final screenHeight = MediaQuery.of(context).size.height;
final screenWidth = MediaQuery.of(context).size.width;
final logoHeight = screenHeight * 0.4;
return Scaffold(
backgroundColor: Colors.white,
body: FutureBuilder(
future: ref.getProfileUrl(user.uid),
builder: (BuildContext context, AsyncSnapshot<String> url) {
if (url.connectionState == ConnectionState.waiting) {
return Loading(
size: 20,
);
}
if (url.hasData) {
return StreamBuilder<DocumentSnapshot>(
stream: DatabaseService(uid: user.uid).userData,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Loading(
size: 15,
);
}
if (snapshot.data == null) {
return Loading(
size: 15,
);
}
var userData = snapshot.data;
String _imageUrl = url.data;
if (snapshot.hasData) {
List books = userData['audio_read'];
if (books == null) {
return Loading(
size: 15,
);
//this
}
return Scaffold(
body: Stack(
children: <Widget>[
Transform.translate(
offset: Offset(screenWidth * 0.4, 10),
child: Transform.rotate(
angle: -0.1,
child: SvgPicture.asset(
logo,
height: logoHeight,
color: logoTintColor,
),
),
),
SingleChildScrollView(
child: Column(
children: <Widget>[
SizedBox(
height: 60,
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16.0),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
//
createFirstNameHeader(
user, ref, userData),
Padding(
padding: const EdgeInsets.only(
right: 16.0, bottom: 16, top: 16),
child: Material(
elevation: 4,
borderRadius:
const BorderRadius.all(
Radius.circular(12)),
child: Padding(
padding: const EdgeInsets.only(
left: 16.0,
right: 16.0,
top: 16.0,
bottom: 32.0),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Text(
"TOTAL TALES PLAYED",
style:
hoursPlayedLabelTextStyle,
),
],
),
SizedBox(
height: 4,
),
Text(
"${books.length.toString()} ${books.length > 1 ? "Tales" : "Tale"}",
style: hoursPlayedTextStyle
.copyWith(
color: Color(
0xff5E17EB)),
)
],
),
),
),
),
ContentHeadingWidget(
heading: "Continue listening"),
for (var i = books.length - 1;
i >= 0;
i--)
books.length > 0
? Slidable(
actionExtentRatio: 0.25,
actionPane:
SlidableDrawerActionPane(),
secondaryActions: <Widget>[
IconSlideAction(
caption: 'Delete',
color: Colors.red,
icon: Icons.delete,
onTap: () => {
_deletePressed(
user,
books.elementAt(
i)[
'audio_id']),
}),
],
child: LastReadBook(
audioId: books.elementAt(
i)['audio_id'],
audio_index: int.parse(
books.elementAt(i)[
'audio_index']),
audioSeek: books.elementAt(
i)['audio_seek'],
total: books.elementAt(
i)['total'],
progress: int.parse(books.elementAt(i)['audio_index']) /
books.elementAt(
i)["totalIndex"],
description:
"${books.elementAt(i)["audio_index"]} of ${books.elementAt(i)["totalIndex"]} episodes",
image: books
.elementAt(i)['image']),
)
: Loading(
size: 15,
),
],
),
),
],
),
)
],
),
);
} else {
return Loading(
size: 15,
);
}
});
} else {
return Loading(
size: 15,
);
}
}),
);
}
Padding createFirstNameHeader(
User user, StorageService ref, DocumentSnapshot userData) {
return Padding(
padding: const EdgeInsets.symmetric(
vertical: 16.0,
),
child: Row(
children: <Widget>[
createProfileImage(user, ref),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: RichText(
text: TextSpan(
children: [
TextSpan(
text: 'Hello',
style: userNameTextStyle,
),
TextSpan(text: '\n'),
TextSpan(
text: userData['firstname'], style: userNameTextStyle),
],
),
),
),
],
),
);
}
createProfileImage(User user, StorageService ref) {
return StreamBuilder(
stream: Firestore.instance
.collection("Users")
.document(user.uid)
.snapshots(),
builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
// return Center(
// child: CircularProgressIndicator(),
// );
return Loading(
size: 15,
);
}
if (snapshot.data == null) {
return Loading(
size: 15,
);
}
print(snapshot.data.data);
return GestureDetector(
onTap: () async {
if (user.uid != HomeScreen.defaultUID) {
dynamic imageFromUser = await ref.getImage();
await ref.addImageToFirebase(user.uid, imageFromUser);
} else {
createAccountDialouge(context);
}
},
child: RoundedImageWidget(
imagePath: snapshot.data["profile_image"],
icon: Icons.photo_camera,
showIcon: true),
);
});
}
createAccountDialouge(BuildContext context) {
return showDialog(
context: context,
child: CupertinoAlertDialog(
title: Text('Avid Tale Would Like to Enable Full Access'),
content: Text('Creating an account will enable access to this feature'),
actions: <Widget>[
CupertinoDialogAction(
child: Text('Cancel'),
onPressed: () {
Navigator.pop(context);
},
),
CupertinoDialogAction(
child: Text('Register'),
onPressed: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return RegisterScreen();
},
),
);
},
)
],
),
);
}
void _deletePressed(user, bookId) async {
DatabaseService userService = DatabaseService(uid: user.uid);
DocumentSnapshot documentSnapshot =
await Firestore.instance.collection("Users").document(user.uid).get();
var data = documentSnapshot.data["audio_read"];
data.retainWhere((element) => element["audio_id"] != bookId);
await userService.updateUserData({'audio_read': FieldValue.delete()});
await userService
.updateUserData({'audio_read': FieldValue.arrayUnion(data)});
}
}
Every time you delete an item, it triggers a new event in the Stream. As the Stream is retrieving/processing the new data it goes into this if block of code as the connectionState changes to waiting:
if (snapshot.connectionState == ConnectionState.waiting) {
return Loading(
size: 15,
);
}
Simply removing this block of code will should stop the "flickering". You may need to include other checks of data availability if necessary for your application.