Show loading indicator /spinner when the page data isn't fully loaded from Firebase - Flutter - firebase

In my Flutter app, I am using ModalProgressHUD to show a spinner when I click on save buttons in my form screens and it stops spinner once data successfully writes to Firebase.
I have this screen that uses Listview.builder to display a list of all my expenses and I want to automatically show spinner as soon as the page displays, and to stop spinner once all the data from Firebase fully loads.
I need assistance in doing this. I've pasted excerpt of my code as shown below. Thanks in advance.
//class wide declaration
bool showSpinner = true;
Widget build(BuildContext context) {
ExpenseNotifier expenseNotifier = Provider.of<ExpenseNotifier>(context);
Future<void> _resfreshList() async {
expenseNotifier.getExpenses(expenseNotifier);
var expenseList = ExpenseNotifier.getExpenses(expenseNotifier);
if (expenseList != null) {
setState(() {
showSpinner = false;
});
}
return Scaffold(
body: ModalProgressHUD(
inAsyncCall: showSpinner,
child: RefreshIndicator(
onRefresh: _resfreshList,
child: Consumer<ExpenseNotifier>(
builder: (context, expense, child) {
return expense == null
? Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
PaddingClass(bodyImage: 'images/empty.png'),
SizedBox(
height: 20.0,
),
Text(
'You don\'t have any expenses',
style: kLabelTextStyle,
),
],
)
: ListView.separated(
itemBuilder: (context, int index) {
var myExpense = expense.expenseList[index];
return Card(
elevation: 8.0,
color: Colors.white70,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
RegularExpenseTextPadding(
regText:
'${_formattedDate(myExpense.updatedAt)}',
),
Container(
margin: EdgeInsets.all(20.0),
padding: const EdgeInsets.all(15.0),
decoration: BoxDecoration(
borderRadius:
BorderRadius.all(Radius.circular(5.0)),
border: Border.all(
color: kThemeStyleBorderHighlightColour),
),
child: Row(
children: <Widget>[
Expanded(
flex: 5,
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Text(
'${myExpense.amount}',
style: kRegularTextStyle,
),
SizedBox(
height: 20.0,
),
Text(
myExpense.description,
style: kRegularTextStyle,
),
],
),
),
Expanded(
flex: 1,
child: GestureDetector(
onTap: () {
expenseNotifier.currentExpense =
expenseNotifier
.expenseList[index];
Navigator.of(context).push(
MaterialPageRoute(builder:
(BuildContext context) {
return ExpenseDetailsScreen();
}));
},
child: Icon(
FontAwesomeIcons.caretDown,
color: kThemeIconColour,
),
),
),
],
),
),
],
),
);
},
separatorBuilder: (BuildContext context, int index) {
return SizedBox(
height: 20.0,
);
},
itemCount: expenseNotifier.expenseList.length,
);
},
),
),
),
);
}

this is an example from my app:
bool _isLoading = false; <- default false
bool _isInit = true; <- to mae it only load once
#override
void initState() {
if (_isInit) {
// activating spinner
_isLoading = true;
// your function here <------
_isInit = false;
super.initState();
}
Initstate gets called before the user can see any kind of thin in your app, so this is the perfect place to make your firebase data load. with this logic from above the loading spinner shows as long you are receiving the data. And your body looks like the following then:
#override
Widget build(BuildContext context) {
return _isLoading <- is loading condition true? shows spinner
? Center(child: CircularProgressIndicator()) <- loading spinner
// else shows your content of the app
: SafeArea(
child: Container()
....

Related

Flutter PlatformException in FutureBuilder

I'm getting the below PlatformException in a FutureBuilder when running app.release.apk on an Android phone. It doesn't happen every time.
I noticed that if I have the app open and I close the phone, after opening it and visiting the first item from a ListView shows the error, sometimes following visits to other items causes the exception, sometimes not.
PlatformException(Error performing get, Failed to get document because the client is offline., null
class _ItemState extends State<Item> {
Future _itemFuture;
#override
void initState() {
setState(() {
_itemFuture = Firestore.instance
.collection('content')
.document(widget.item.documentID)
.get();
});
...
super.initState();
}
Scaffold(
body: Container(
child: FutureBuilder<DocumentSnapshot>(
future: _itemFuture,
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Container();
case ConnectionState.waiting:
return Center(
child: CircularProgressIndicator(),
);
default:
if (snapshot.hasError) {
return Text('Error1: ${snapshot.error}');
} else {
if (snapshot.hasData) {
return _itemBody(
snapshot.data,
);
}
}
return null;
}
},
),
),
);
I am using:
cloud_firestore: ^0.13.7
firebase_auth: ^0.16.1
*** Edit
I will add the whole widget. I cleaned it, removing any other logic that I thought might cause the error. Now it's a minimal widget that makes a request to Firestore using Streambuilder. Of course with the same error.
class Item extends StatefulWidget {
Item({
Key key,
this.items,
this.showAd,
this.user,
this.item,
this.favorites,
}) : super(key: key);
final List<Imodel> items;
final bool showAd;
final UserModel user;
final item;
final List<FireFavorites> favorites;
#override
_ItemState createState() => _ItemState();
}
class _ItemState extends State<Item> {
DateTime _lastViewed;
bool _viewRequest = true;
final _adWidget = AdMobWidget();
bool _favoriteItem = false;
#override
void initState() {
super.initState();
final isFavorite = widget.favorites
.where((element) => element.id == widget.item.documentID);
if (isFavorite.length > 0) {
_favoriteItem = true;
}
}
#override
Widget build(BuildContext context) {
if (widget.showAd) {
_adWidget.showAd();
}
final _headerStyle = TextStyle(fontWeight: FontWeight.bold);
Widget _itemBody(item) {
return ListView(
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
...
],
),
],
);
}
_future() {
return FutureBuilder<DocumentSnapshot>(
future: Firestore.instance
.collection('content')
.document(widget.item.documentID)
.get(source: Source.serverAndCache),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
List<Widget> children;
if (snapshot.hasData) {
children = <Widget>[Expanded(child: _itemBody(snapshot.data))];
} else if (snapshot.hasError) {
children = <Widget>[
Icon(
Icons.error_outline,
color: Colors.red,
size: 60,
),
Padding(
padding: const EdgeInsets.only(top: 16),
child: Text('Error: ${snapshot.error}'),
)
];
} else {
children = <Widget>[
SizedBox(
child: CircularProgressIndicator(),
width: 60,
height: 60,
),
const Padding(
padding: EdgeInsets.only(top: 16),
child: Text('Awaiting result...'),
)
];
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: children,
),
);
},
);
}
return Scaffold(
resizeToAvoidBottomPadding: false,
backgroundColor: Color(0xff2398C3),
appBar: AppBar(
elevation: 0,
flexibleSpace: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Color(0xff042C5C), Color(0xff2398C3)],
),
),
),
actions: <Widget>[
BookmarkIcon(
isFav: _favoriteItem,
documentID: widget.item.documentID,
userID: widget.user.uid,
),
Padding(
padding: EdgeInsets.only(
right: 20.0,
),
child: GestureDetector(
onTap: () {},
child: Icon(
Icons.share,
size: 18.0,
),
),
),
],
),
body: Container(
width: double.infinity,
height: double.infinity,
padding: EdgeInsets.only(
top: 25.0,
left: 30.0,
right: 15.0,
),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(32),
topRight: Radius.circular(32),
),
),
child: widget.item.documentID != null ? _future() : Container(),
),
);
}
}

No such method error while calling a function

I retrieved products data from Firebase for my E-commerce homepage through future builder. I've created another screen that displays more information on a product when the user clicks on a product from the E-commerce homepage.To navigate to more information screen i created a function called showProduct and called it with a button, but when the button id pressed it shows
NoSuchMethodError: The method '[]' was called on null.Receiver: null Tried calling .
The showProduct function ] was also used on the vendor profile page where the products shown are shown in gridview and when clicked on any product from the vendors's profile.The showProduct function works and open more information screen.
E-commerce Homepage:
c
lass Shop extends StatefulWidget {
final Prod products;
final User currentUser;
final String prodId;
final String onwerId;
Shop({ this.currentUser,
this.prodId,
this.products,
this.onwerId});
#override
_ShopState createState() => _ShopState( prodId: this.prodId,products: this.products,ownerId:this.onwerId);
}
class _ShopState extends State<Shop> {
String postOrientation = "grid";
String shopOrientation = "grid";
bool isFollowing = false;
bool isLoading = false;
String uid="";
String prodId;
String ownerId;
Prod products;
_ShopState({
this.prodId, this.products,this.ownerId,
});
#override
void initState() {
super.initState();
showProduct;
}
Future getProducts()async {
var firestore = Firestore.instance;
QuerySnapshot snap = await firestore.collectionGroup("userProducts").getDocuments();
return snap.documents;
}
Future<Null>getRefresh()async{
await Future.delayed(Duration (seconds : 3));
setState(() {
getProducts();
});
}
showProduct(context) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductScreen(
prodId: prodId,
userId: ownerId,
),
),
);
}
#override
Widget build(BuildContext context) {
return
Scaffold(
appBar: AppBar(backgroundColor: kSecondaryColor,
title: Text( 'Shop',
style: TextStyle(
fontFamily :"MajorMonoDisplay",
fontSize: 35.0 ,
color: Colors.white),),
iconTheme: new IconThemeData(color: kSecondaryColor),
),
backgroundColor: kPrimaryColor,
body:FutureBuilder(
future: getProducts(),
builder: (context,snapshot)
{
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: circularProgress(),);
} else {
return
RefreshIndicator(
onRefresh: getRefresh,
child: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
var ourdata = snapshot.data[index];
return
Container(
height: 500,
margin: EdgeInsets.only(
top: 1.0, left: 10.0, right: 10.0, bottom: 1.0),
child: Column( children: <Widget>[
SizedBox( height:1.0,),
Stack(
children: <Widget>[
Container(
child:Row(
children: <Widget>[
Expanded(
child: Container(
height: 400.0,
child: ClipRRect(borderRadius: BorderRadius.circular(20.0),
child: cachedNetworkImage(ourdata.data['shopmediaUrl'],
),
),
),
),
],
),
),
Expanded(
child: Positioned(
bottom: 10,
left: 10,
child: Container(
height: 40,
width: 40,
child: ClipRRect(
borderRadius: BorderRadius.circular(40.0),
child: Image.network(ourdata.data['photoUrl'],)),
),
),
),
Expanded(
child: Positioned(
bottom: 20,
left: 60,
child: Container(
child: Text(ourdata.data['username'],style: TextStyle(color: Colors.white,fontWeight:FontWeight.bold),),
),
),
),
Container(
alignment: Alignment.bottomRight,
child: GFButton(
onPressed: () => showProduct(context) ,
text: "More",
icon: Icon(Icons.card_travel),
shape: GFButtonShape.pills,
),
),
],
),
Row(
children: <Widget>[
Container(
child: Text(ourdata.data['productname'],style: TextStyle(color: kText,fontSize: 30.0,fontWeight:FontWeight.bold),),
),
],
),
Row(
children: <Widget>[
Container( child: Text('₹',style: TextStyle(color: kText,)),
),
Container(
child: Text(ourdata.data['price'],style: TextStyle(color: kText,fontSize: 20.0,fontWeight:FontWeight.bold),),
),
],
),
Divider(color: kGrey,),
],
),
);
}
)
);
}
}
),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.black38,
onPressed: ()
async{ Navigator.push(context, MaterialPageRoute(builder: (context) =>Uploadecom(currentUser: currentUser, )));
},
child: Icon(Icons.add_box),
),
);
}
}
This is the gridview on the vendor's profile.
class ProductTile extends StatelessWidget {
final Prod products;
ProductTile(this.products);
showProduct(context) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductScreen(
prodId: products.prodId,
userId: products.ownerId,
),
),
);
}
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => showProduct(context),
child: cachedNetworkImage(products.shopmediaUrl),
);
}
}
If you need more codes please ask me.

Download data from firebase Firestore to flutter

I am using Firestore as a database for a Chat in one part of the application that I am building. I have a collection on my Firestore that looks like this:
messages(collection)
userId
userId-otherUserId(sub-collection)
randomId
content : String,
timestamp : Date
...
and I would like to retrieve firstly all of the userIs-otherUserId in a ListView and then to retrieve the lastMessage by retrieving the last randomId(and in that randomId the last message is the last element with key 'content') and I would like it to look something like this.
Prototype
where the Loading represents last message but the name and profilePicture I can get from my API.
The pictures of my Firestore database:
First Image
Second Image
Third Image
Is there any chance that I could save the name and Profile picture on the database in the userId-otherUserId(collection)?
The code:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:dio/dio.dart';
import 'package:disby_app/const.dart';
import 'package:disby_app/data/request_model.dart';
import 'package:disby_app/global_widgets/loading_indicator.dart';
import 'package:disby_app/main_screens/main_chat_and_request_screens/chat.dart';
import 'package:disby_app/main_screens/main_chat_and_request_screens/profile_details_screen.dart';
import 'package:disby_app/public/keys.dart';
import 'package:disby_app/services/json_requests.dart';
import 'package:flutter/material.dart';
import 'package:flutter_translate/flutter_translate.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../global_widgets/chat_and_requests_placeholder.dart';
class MainChatScreen extends StatefulWidget {
#override
_MainChatScreenState createState() => _MainChatScreenState();
}
class _MainChatScreenState extends State<MainChatScreen> {
bool _areThereChats = false;
bool _isLoading = true;
String groupChatId;
String userId = '1';
List<String> listOfLastMessages = [];
List<String> listOfIds = [];
List<ArrayOfRequestsModel> arrayOfRequests = [];
final GlobalKey<AnimatedListState> _listKey = GlobalKey();
Future readLocal() async {
var prefs = await SharedPreferences.getInstance();
userId = prefs.getString(kUserId) ?? '';
print(userId);
setState(() {});
}
Future<void> _getRequests() async {
final prefs = await SharedPreferences.getInstance();
final userId = prefs.getString(kUserId);
try {
await Dio().post(baseUrl + acceptedUsers + "/" + userId).then((snapshot) {
print(snapshot);
final Map<String, dynamic> response = snapshot.data;
print(response);
if (response['response'] == 'success') {
List<dynamic> arrayFromServer = response['acceptedUsers'];
if (arrayFromServer.isNotEmpty) {
arrayFromServer.forEach((userData) {
arrayOfRequests.add(ArrayOfRequestsModel.fromJson(userData));
listOfIds.add(userData['userId']);
print(userData['userId']);
});
_areThereChats = true;
_isLoading = false;
getMessages(userId);
} else {
_areThereChats = false;
_isLoading = false;
}
setState(() {});
} else {
_areThereChats = false;
_isLoading = false;
setState(() {});
}
});
} catch (e) {
print(e);
}
}
getMessages(String userId) {
int i = 0;
print(listOfIds.length);
print(listOfIds);
listOfIds.forEach((element) {
Firestore.instance
.collection('messages')
.document('$userId')
.collection('$userId-$element')
.orderBy('timestamp', descending: true)
.limit(3)
.getDocuments()
.then((QuerySnapshot snapshot) {
print(snapshot.documents[0].data['content']);
snapshot.documents.forEach((f) {
print(f.data['content']);
listOfLastMessages.add(f.data['content']);
setState(() {});
i++;
});
if (i == listOfIds.length) {
setState(() {});
print(listOfLastMessages);
}
});
});
}
#override
void initState() {
readLocal();
_getRequests();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Container(
width: double.infinity,
height: double.infinity,
child: SingleChildScrollView(
// child: (userId != '1')
// ? StreamBuilder(
// stream: Firestore.instance
// .collection('messages')
// .document('5ef4d83175b07cf074525c08')
// .snapshots(),
// builder: (context, snapshot) {
// // if (snapshot.hasData) {
// if (!snapshot.hasData) {
// return Center(
// child: CircularProgressIndicator(
// valueColor: AlwaysStoppedAnimation<Color>(themeColor),
// ),
// );
// } else {
// return Container(
// width: 100,
// height: 200,
// child: ListView.builder(
// padding: EdgeInsets.all(10.0),
// itemBuilder: (context, index) =>
// buildItem(context, snapshot.data.documents),
// itemCount: snapshot.data.documents.length,
// ),
// );
// }
// },
// )
// : LoadingIndicator(
// loading: _isLoading,
// ),
// ),
child: Column(
children: <Widget>[
(_isLoading == false)
? (_areThereChats == true)
? Container(
child: AnimatedList(
key: _listKey,
shrinkWrap: true,
initialItemCount: arrayOfRequests.length,
itemBuilder:
(BuildContext context, index, animation) {
return _buildItem(context, arrayOfRequests[index],
animation, index);
},
),
)
: ChatAndRequestPlaceholder(
text: translate('when_someone_sends_you_a_request'))
: LoadingIndicator(
loading: _isLoading,
),
],
),
),
),
);
}
Widget buildItem(BuildContext context, DocumentSnapshot document) {
if (document['id'] == userId) {
return Container();
} else {
return Container(
child: FlatButton(
child: Row(
children: <Widget>[
Flexible(
child: Container(
child: Column(
children: <Widget>[
Container(
child: Text(
'Nickname: ${document['content']}',
style: TextStyle(color: primaryColor),
),
alignment: Alignment.centerLeft,
margin: EdgeInsets.fromLTRB(10.0, 0.0, 0.0, 5.0),
),
Container(
child: Text(
'About me: ${document['content'] ?? 'Not available'}',
style: TextStyle(color: primaryColor),
),
alignment: Alignment.centerLeft,
margin: EdgeInsets.fromLTRB(10.0, 0.0, 0.0, 0.0),
)
],
),
margin: EdgeInsets.only(left: 20.0),
),
),
],
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Chat(
peerId: document.documentID,
peerAvatar: document['photoUrl'],
),
),
);
},
color: greyColor2,
padding: EdgeInsets.fromLTRB(25.0, 10.0, 25.0, 10.0),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
),
margin: EdgeInsets.only(bottom: 10.0, left: 5.0, right: 5.0),
);
}
}
_buildItem(BuildContext context, ArrayOfRequestsModel arrayOfSentRequests,
Animation animation, int index) {
return GestureDetector(
onTap: () {
print(arrayOfSentRequests.profilePictureUrl);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Chat(
peerId: arrayOfSentRequests.userId,
peerAvatar: arrayOfSentRequests.profilePictureUrl,
),
),
);
},
child: Container(
height: 82,
child: ScaleTransition(
scale: animation,
child: Padding(
padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Color.fromRGBO(0, 0, 0, 0.07),
offset: Offset(0, 5),
blurRadius: 11,
),
],
),
width: double.infinity,
height: 78,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Container(
height: double.infinity,
child: GestureDetector(
onTap: () {
Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute(
builder: (context) => ProfileDetailsScreen(),
),
);
},
child: Row(
children: <Widget>[
SizedBox(width: 24),
ClipRRect(
borderRadius: BorderRadius.circular(25),
child: Image(
image: NetworkImage(
arrayOfSentRequests.profilePictureUrl,
),
width: 48,
),
),
SizedBox(width: 10),
Expanded(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
arrayOfSentRequests.nameAndSurname,
style: TextStyle(
color: Colors.black,
fontFamily: 'Avenir',
fontWeight: FontWeight.w700,
fontSize: 18,
),
),
Text(
'11/11/2020', //arrayOfSentRequests.nameAndSurname
style: TextStyle(
color: Colors.grey,
fontFamily: 'Avenir',
fontWeight: FontWeight.w500,
fontSize: 15,
),
),
],
),
),
Container(
child: Text(
// (arrayOfSentRequests.lastMessage !=
// null)
// ? arrayOfSentRequests.lastMessage
// : 'Loading..',
(listOfLastMessages.isNotEmpty)
? listOfLastMessages[index]
.toString()
: 'Loading...',
maxLines: 2,
softWrap: true,
style: TextStyle(
color: Colors.black54,
fontFamily: 'Avenir',
fontSize: 15,
),
),
),
],
),
),
),
SizedBox(width: 10),
],
),
),
),
),
Container(
child: Center(
child: Icon(
Icons.keyboard_arrow_right,
size: 22,
color: Colors.black54,
),
),
),
SizedBox(width: 10),
],
),
),
),
),
),
);
}
}

Initialize App using FutureBuilder with a ListView.builder and have an onClick in each ListItem?

Im building an App with Flutter and have a problem regarding the use of FutureBuilder. The situation is that my HomePage in the App should make a request to my server and get some Json. The call to the getData-Method happens in the build-method of the Homescreen (not sure if this is right).
The next call in the build-Method has the snapshot and builds a ListView.
Here is the problem:
Each time I click a button or go to a different screen, the Future Builder is triggered! That means that I have a bunch of useless API calls.
Here is the question:
What do I have to change, to let the Future Builder only run when I come to the Homescreen?
class HomeState extends State<Home> {
int count = 0;
final homeScaffoldKey = GlobalKey<ScaffoldState>();
List compList = new List();
Future<List> getData() async {
final response = await http.get(
Uri.encodeFull("http://10.0.2.2:5000/foruser"),
headers: {
"Authorization":
"JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NTk2NDM4ODcsImlhdCI6MTU1NzA1MTg4NywibmJmIjoxNTU3MDUxODg3LCJpZGVudGl0eSI6MX0.OhuUgX9IIYFX7u0o_6MXlrMYwk7oMCywlmHLw-vbNSY",
"charset": "utf-8"
},
);
if (response.statusCode == 200) {
compList = jsonDecode(response.body);
List<Comp> result = [];
count++;
for (var c in compList) {
Comp comp = Comp.fromJson(c);
result.add(comp);
}
return result;
} else {
throw Exception('Failed to load');
}
}
#override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.white10,
body: Stack(
children: <Widget>[
new Container(
child: FutureBuilder(
future: getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.data == null) {
return new Container(
child: Text("whoops"),
);
}
if (snapshot.hasData) {
if (snapshot.data != null) {
if (snapshot.data.toString() == "[]") {
print("no comps - called API: $count");
return new ListView(
key: Key("1"),
children: <Widget>[
new Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
SizedBox(
height: 30.0,
),
Card(
color: Colors.blue,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
title: Text(
"Welcome, you have no comps",
style:
TextStyle(color: Colors.white),
),
),
],
),
),
],
),
],
);
}
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
print(index);
if (index == 0) {
return new Column(
children: <Widget>[
Card(
color: Colors.blue,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
title: Text(
"Welcome back, these are your comps",
style:
TextStyle(color: Colors.white),
),
),
],
),
),
SizedBox(
height: 10.0,
),
new CompListItem(
new Comp(
snapshot.data[index].left_name,
snapshot.data[index].right_name,
snapshot.data[index].left,
snapshot.data[index].right,
snapshot.data[index].left_city,
snapshot.data[index].right_city,
snapshot.data[index].latitude_left,
snapshot.data[index].longitude_left,
snapshot.data[index].latitude_right,
snapshot.data[index].longitude_right,
snapshot.data[index].points,
),
"left")
],
);
}
Comp tmp = new Comp(
snapshot.data[index].left_name,
snapshot.data[index].right_name,
snapshot.data[index].left,
snapshot.data[index].right,
snapshot.data[index].left_city,
snapshot.data[index].right_city,
snapshot.data[index].latitude_left,
snapshot.data[index].longitude_left,
snapshot.data[index].latitude_right,
snapshot.data[index].longitude_right,
snapshot.data[index].points,
);
return new CompListItem(tmp, "left");
},
);
} else if (snapshot.data == null) {
return new Container(
child: Text("Sorry, there seems to be a problem :("),
);
}
}
} else {
return CircularProgressIndicator();
}
},
),
),
],
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
FloatingActionButton(
heroTag: null,
child: Icon(
Icons.add_location,
color: Colors.white,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MakeComp(),
),
);
},
backgroundColor: Colors.blue,
),
SizedBox(
height: 10.0,
),
FloatingActionButton(
heroTag: null,
child: Icon(Icons.compare_arrows),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => GetComps(),
),
);
},
backgroundColor: Colors.blue,
),
],
));
}
}
Actual results:
Open the App -> Future Builder runs -> List of data is shown -> Navigate to another Widget -> Future Builder runs -> click some button -> Future Builder runs
Expected results:
Open the App -> Future Builder runs -> List of data is shown -> Navigate to another Widget -> click some button -> do something on another screen -> return to homescreen -> Future Builder runs
And in the moment I posted this question, I found my answer :D
Thanks to Rémi Rousselet, who answerd this question here:
How to deal with unwanted widget build?
The answer was simply to put the call for the Future into the initState Method, which is exactly called, when I need the data to be loaded.
Happy Fluttering everyone!

Displaying Firebase Firestore Listview Data as a list Flutter

I am currently able to display a Listview filled with data from my Firestore database. My current problem is, that I want to make it dissmissable, so I need to be able to use functions such as:
setState(() {
items.removeAt(index);
});
Now, I read up on how to generate a list, but none of the examples mention a firebase Streambuilder like I am using. So I was just wondering if it was possible to make the data into a list? And if not, if there are any other ways to make a firestore listview dissmissable? Here is how I currently get the data:
Container(
child: StreamBuilder(
stream: Firestore.instance.collection('users').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(themeColor),
),
);
} else {
return ListView.builder(
scrollDirection: Axis.vertical,
padding: EdgeInsets.all(10.0),
itemBuilder: (context, index) => buildItem(context, snapshot.data.documents[index]),
itemCount: snapshot.data.documents.length,
);
}
},
),
),
Thanks in advance, any help is appreciated.
Builditem looks like this:
Widget buildItem(BuildContext context, DocumentSnapshot document) {
if (document['id'] == currentUserId || document['gender'] == null) {
return Container();
}
if (currentUserPreference == 'male' && currentUserGender == 'male') {
return showGayMales(document);
}
And the ShowGayMales method looks like this:
Widget showGayMales(DocumentSnapshot document) {
if (document['id'] == currentUserId || document['id'] == nopeId || ) {
return Container();
} else {
return Container(
child: Slidable(
delegate: new SlidableScrollDelegate(),
actionExtentRatio: 0.3,
child: Card(
child: Padding(
padding:EdgeInsets.fromLTRB(20.0, 10.0, 25.0, 10.0),
child: Row(
children: <Widget>[
Material(
color: Colors.transparent,
child: Icon(
FontAwesomeIcons.male,
color: textColor,
),
),
new Flexible(
child: Container(
child: new Column(
children: <Widget>[
new Container(
child: Text(
'${document['aboutMe']}',
style: TextStyle(color: textColor, fontSize: 30.0),
),
alignment: Alignment.centerLeft,
margin: new EdgeInsets.fromLTRB(10.0, 0.0, 0.0, 5.0),
),
new Container(
child: Row(
children: <Widget>[
Text(
'-'+'${document['nickname'] ?? 'Not available'}',
style: TextStyle(color: textColor, fontSize: 15.0, fontWeight: FontWeight.bold),
),
Text(
','+' ${document['age'] ?? ''}'
)
],
),
alignment: Alignment.centerLeft,
margin: new EdgeInsets.fromLTRB(10.0, 0.0, 0.0, 0.0),
)
],
),
margin: EdgeInsets.only(left: 20.0),
),
),
],
),
),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
),
actions: <Widget>[
new IconSlideAction(
caption: 'Not interested!',
color: errorColor,
icon: Icons.clear,
onTap: () => notinterested('${document['id']}'),
),
],
secondaryActions: <Widget>[
new IconSlideAction(
caption: "Interested!",
color: primaryColor,
icon: Icons.check,
onTap: () => interested('${document['nickname']}', '${document['id']}', '${document['gender']}', '${document['aboutMe']}', '${document['age']}', '${document['preference']}'),
),
],
),
margin: EdgeInsets.only(bottom: 10.0, left: 5.0, right: 5.0),
);
}
}
You can fetch Firestore data and add it to a List by mapping it to an Object first.
List<Users> userList;
Future<void> getUsers() async {
userList = [];
var collection = FirebaseFirestore.instance.collection('users');
collection.get().then((value) {
value.docs.forEach((users) {
debugPrint('get Users ${users.data()}');
setState(() {
// Map users.data to your User object and add it to the List
userList.add(User(User.setUserDetails(users.data())));
});
});
});
}
// Let's say this is User object
class User {
var username;
User(User doc) {
this.username = doc.getUsername();
}
getUsername() => username;
// fetch name using Firestore field name
User.setUserDetails(Map<dynamic, dynamic> doc)
: username = doc['name'];
}

Resources