How to show a dialog with FutureBuilder when press a button? - firebase

I upload an image FirebaseStorage with FutureBuilder and when I press upload button I want to show a waiting dialog. Image upload successfully on FireStorage but nothing shows up. Whats wrong my codes? I think FutureBuilder return Widget and press button void. Maybe it is the problem. Or I am calling FutureBuilder wrong way. Do you have any tips or suggestions for my wrong code?
Here is my code;
Widget buildBody(BuildContext context) {
return new SingleChildScrollView(
child: new Column(
children: [
new SizedBox(
width: double.infinity,
child: new RaisedButton(
child: new Text('Upload'),
onPressed: () {
futureBuilder();
},
),
),
],
),
);
}
Future mediaUpload() async {
final fileName = DateTime.now().millisecondsSinceEpoch.toString() + '.jpg';
final StorageReference storage = FirebaseStorage.instance.ref().child(fileName);
final StorageUploadTask task = storage.putFile(_image);
return task.future;
}
Widget futureBuilder() {
return new FutureBuilder(
future: mediaUpload(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
print('ConnectionState.none');
return new Text('Press button to start.');
case ConnectionState.active:
print('ConnectionState.active');
return new Text('');
case ConnectionState.waiting:
waitingDialog(context);
return waitingDialog(context);
case ConnectionState.done:
print('ConnectionState.done');
if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
print(snapshot.data.downloadUrl);
Navigator.of(context).pushReplacementNamed('home');
return new Text('Result: ${snapshot.data.downloadUrl}');
}
},
);
}
waitingDialog(BuildContext context) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return new Center(
child: new SizedBox(
width: 40.0,
height: 40.0,
child: const CircularProgressIndicator(
value: null,
strokeWidth: 2.0,
),
),
);
},
);
}

I am not 100% sure why FutureBuilder is not working. But I have a guess. In the above example, FutureBuilder is not attached to the widgetTree(screen). Not attached means value returned from FutureBuilder is not displayed in screen. In this case, Text is returned based on snapshot.connectionState which is not attached to screen.
Work around: (I tested and it worked, can you please verify)
futureBuilder(BuildContext context) {
mediaUpload().then((task) { // fire the upload
Navigator.of(context).maybePop(); // remove the dialog on success upload
}); // we can use task(which returned from
// mediaUpload()) to get the values like downloadUrl.
waitingDialog(context); // show the spinner dialog
}

Related

How to invisible widget when there is no data in firebase?

i am new to flutter, i'm trying to invisible button when there is no data in Firebase.
To get data i'm using StreamBuilder, if snapshot.data!.docs is null i want to invisible CustomButton which is outside of StreamBuilder.
StreamBuilder:
bool _isVisible = true; //variable
#override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Scaffold(
key: _scaffoldKey,
appBar: _appBar(context),
body: CommonRefreshIndicator(
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('users')
.doc(_currentUser!.uid)
.collection('favourites')
.snapshots(),
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return const CustomProgressIndicator();
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const CustomProgressIndicator();
}
final data = snapshot.data!.docs;
allData = snapshot.data!.docs;
if (data.isNotEmpty) { //update based on data
_isVisible = true;
} else {
_isVisible = false;
}
return data.isNotEmpty
? _favItemListView(data)
: const Center(
child: Text('No data found'),
);
},
),
),
bottomNavigationBar: _addAllToFavButton(size),
);
}
CustomButton:
Padding _addAllToFavButton(Size size) => Padding(
padding: kSymmetricPaddingHor,
child: Visibility(
visible: _isVisible,
child: CustomButton(
label: 'Add all to my cart',
onPressed: () {},
),
),
);
i have tried with Visibility widget and its work but whenever i'm deleting all data CustomButton is still visible, to invisivle CustomButton every time need to do hot reload.
NOTE: setState is also not working its giving me error.
if any one can help me! Thanks.
If you want to hide your CustomButton when there is no data you can try this:
Put your _favItemListView(data) & _addAllToFavButton(size) inside Stack and give Positioned to your CustomButton with its bottom : 1 property.
StreamBuilder
return data.isNotEmpty
? Stack(
children: [
_favItemListView(data),
_addAllToFavButton(size),
],
)
: const Center(
child: Text('No data found'),
);
CustomButton:
Positioned _addAllToFavButton(Size size) => Positioned(
width: size.width,
bottom: 1, //bottom property
child: Padding(
padding: kSymmetricPaddingHor,
child: CustomButton(
label: 'Add all to my cart',
onPressed: () {}
},
),
),
);
You can check if the snapshot has any data by using snapshot.data!.data()!.isNotEmpty
then
if(snapshot.data!.data()!.isNotEmpty){
//show your data widget
// using a variable might require you to call a setstate but since
//the widget is building here you might get some errors, its safe to just show your widget if data exists
}else{
///no data here
}
Also to get the .data() you need to tell your stream that its a of type <DocumentSnapshot<Map<String, dynamic>>> as . .snapshots() returns Stream<DocumentSnapshot<Map<String, dynamic>>>
StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore.instance..

Can't get actual String download url from Firebase Storage and only returns Instance of 'Future<String>' even using async/await

I am trying to get user avatar from firebase storage, however, my current code only returns Instance of 'Future<String>' even I am using async/await as below. How is it possible to get actual download URL as String, rather Instance of Future so I can access the data from CachedNewtworkImage?
this is the function that calls getAvatarDownloadUrl with current passed firebase user instance.
myViewModel
FutureOr<String> getAvatarUrl(User user) async {
var snapshot = await _ref
.read(firebaseStoreRepositoryProvider)
.getAvatarDownloadUrl(user.code);
if (snapshot != null) {
print("avatar url: $snapshot");
}
return snapshot;
}
getAvatarURL is basically first calling firebase firestore reference then try to access to the downloadURL, if there is no user data, simply returns null.
Future<String> getAvatarDownloadUrl(String code) async {
Reference _ref =
storage.ref().child("users").child(code).child("asset.jpeg");
try {
String url = await _ref.getDownloadURL();
return url;
} on FirebaseException catch (e) {
print(e.code);
return null;
}
}
I am calling these function from HookWidget called ShowAvatar.
To show current user avatar, I use useProvider and useFuture to actually use the data from the database, and this code works with no problem.
However, once I want to get downloardURL from list of users (inside of ListView using index),
class ShowAvatar extends HookWidget {
// some constructors...
#override
Widget build(BuildContext context) {
// get firebase user instance
final user = useProvider(accountProvider.state).user;
// get user avatar data as Future<String>
final userLogo = useProvider(firebaseStoreRepositoryProvider)
.getAvatarDownloadUrl(user.code);
// get actual user data as String
final snapshot = useFuture(userLogo);
// to access above functions inside of ListView
final viewModel = useProvider(myViewModel);
return SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
child: Container(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
height: 100,
width: 100,
child: Avatar(
avatarUrl: snapshot.data, // **this avatar works!!!** so useProvider & useFuture is working
),
),
SizedBox(height: 32),
ListView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return Center(
child: Column(
children: [
SizedBox(
height: 100,
width: 100,
child: Avatar(
avatarUrl: viewModel
.getAvatarUrl(goldWinners[index].user)
.toString(), // ** this avatar data is not String but Instance of Future<String>
),
),
),
],
),
);
},
itemCount: goldWinners.length,
),
Avatar() is simple statelesswidget which returns ClipRRect if avatarURL is not existed (null), it returns simplace placeholder otherwise returns user avatar that we just get from firebase storage.
However, since users from ListView's avatarUrl is Instance of Future<String> I can't correctly show user avatar.
I tried to convert the instance to String multiple times by adding .toString(), but it didn't work.
class Avatar extends StatelessWidget {
final String avatarUrl;
final double radius;
final BoxFit fit;
Avatar({Key key, this.avatarUrl, this.radius = 16, this.fit})
: super(key: key);
#override
Widget build(BuildContext context) {
print('this is avatar url : ' + avatarUrl.toString());
return avatarUrl == null
? ClipRRect(
borderRadius: BorderRadius.circular(radius),
child: Image.asset(
"assets/images/avatar_placeholder.png",
fit: fit,
),
)
: ClipRRect(
borderRadius: BorderRadius.circular(radius),
child: CachedNetworkImage(
imageUrl: avatarUrl.toString(),
placeholder: (_, url) => Skeleton(radius: radius),
errorWidget: (_, url, error) => Icon(Icons.error),
fit: fit,
));
}
}
Since the download URL is asynchronously determined, it is returned as Future<String> from your getAvatarUrl method. To display a value from a Future, use a FutureBuilder widget like this:
child: FutureBuilder<String>(
future: viewModel.getAvatarUrl(goldWinners[index].user),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
return snapshot.hashData
? Avatar(avatarUrl: snapshot.data)
: Text("Loading URL...")
}
)
Frank actually you gave an good start but there are some improvements we can do to handle the errors properly,
new FutureBuilder(
future: //future you need to pass,
builder: (context, snapshot) {
if (snapshot.hasData) {
return new ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context, i) {
DocumentSnapshot ds = snapshot.data.docs[i];
return //the data you need to return using /*ds.data()['field value of doc']*/
});
} else if (snapshot.hasError) {
// Handle the error and stop rendering
GToast(
message:
'Error while fetching data : ${snapshot.error}',
type: true)
.toast();
return new Center(
child: new CircularProgressIndicator(),
);
} else {
// Wait for the data to fecth
return new Center(
child: new CircularProgressIndicator(),
);
}
}),
Now if you are using a text widget as a return statement in case of errors it will be rendered forever. Incase of Progress Indicators, you will exactly know if it is an error it will show the progress indicator and then stop the widget rendering.
else if (snapshot.hasError) {
}
else {
}
above statement renders until, if there is an error or the builder finished fetching the results and ready to show the result widget.

SetState is causing Futurebuilder to reload the data on every tap

I am using future builder and stream builder to fetch data from firebase and show them on screen.
I have favourite button as well. when I click on favourite_borderLine iconButton. It fetch data from firebase then change the state to favourite_border iconButton.
It also change the state of every other listview.Builder what I want is just to change the icon state on every click not fetching the whole data from database.
This is the initial state
when I tap on favourite icon, Suppose I tapped on first icon then it start loading.
and then all the icons are changed :(
I just want to change the clicked icon state not all icons and do not want the fetch data on click just change the state of button.Here is code.
class TalentScreen1 extends StatefulWidget {
#override
_TalentScreen1State createState() => _TalentScreen1State();
}
class _TalentScreen1State extends State<TalentScreen1> {
bool toggle = false;
#override
Widget build(BuildContext context) {
return BlocProvider<TalentFavCubit>(
create: (context) => TalentFavCubit(),
child: SafeArea(
child: Scaffold(
body: Padding(
padding: const EdgeInsets.all(20.0),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text('Talent Screen 1 home search'),
_retriveAllDocs,
],
),
),
),
),
),
);
}
Widget get _retriveAllDocs => FutureBuilder<QuerySnapshot>(
future: FirebaseRepo.instance.fetchWorkerFormFieldsData(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return CircularProgressIndicator();
if (snapshot.hasError) {
return Text("Something went wrong");
}
if (!snapshot.hasData) {
return Text("Nothing to show");
}
if (snapshot.connectionState == ConnectionState.done) {
final List<DocumentSnapshot> data = snapshot.data.docs;
return theUserInfo(data);
}
return Text("loading");
});
Widget theUserInfo(List<DocumentSnapshot> data) {
return ListView.builder(
shrinkWrap: true,
itemCount: data.length,
itemBuilder: (context, index) {
return FutureBuilder<DocumentSnapshot>(
future: fetch(data[index]['uid']),
builder: (BuildContext context,
AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasError) {
return Text("Something went wrong");
}
if (snapshot.connectionState == ConnectionState.done) {
TalentHireFavModel userData = TalentHireFavModel.fromMap(
data[index].data(), snapshot.data.data());
return Card(
child: Column(
children: <Widget>[
Text(userData.name),
Text(userData.categories),
Text(userData.skills),
Text(userData.country),
Text(userData.phoneNo),
Text(userData.hourlyRate),
Text(userData.professionalOverview),
Text(userData.skills),
Text(userData.expert),
Text(userData.createdAt),
IconButton(
icon: toggle
? Icon(Icons.favorite_border)
: Icon(
Icons.favorite,
),
onPressed: () {
setState(() {
// Here we changing the icon.
toggle = !toggle;
});
}),
],
),
);
}
return Container();
});
});
}
//TODO: Implementation Fix Error
Widget _iconButton(uid) {
return StreamBuilder<QuerySnapshot>(
stream: FirebaseRepo.instance.fetchCurrentUserFavourites().snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
var data = snapshot.data.docs;
// print(snapshot.data.get('uid'));
if (snapshot.hasError) {
return Text('Something went wrong');
}
return IconButton(
icon: data.isEmpty == uid
? Icon(Icons.favorite)
: Icon(Icons.favorite_border),
onPressed: () =>
BlocProvider.of<TalentFavCubit>(context).addTalentFav(uid));
},
);
}
Future<DocumentSnapshot> fetch(data) async =>
await FirebaseRepo.instance.fetchWorkerUserData(data);
}
This is your broken line of code:
future: FirebaseRepo.instance.fetchWorkerFormFieldsData(),
The FutureBuilder documentation starts with:
The future must have been obtained earlier, e.g. during State.initState, State.didUpdateWidget, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted.
A general guideline is to assume that every build method could get called every frame, and to treat omitted calls as an optimization.
And you broke the contract. I have a video that illustrates this in detail. https://www.youtube.com/watch?v=sqE-J8YJnpg
Do what the docs say. TL;DR: Do not create the Future in the parameter to FutureBuilder.

FLUTTER: How to use navigator in streambuilder?

I am trying to navigate inside a streambuilder but I have this error:"setState() or markNeedsBuild() called during build.". If I call navigate inside an onpressed button it works but not by just use it inside a condition. I am stuck. There is some code to show you.
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder(
stream:
Firestore.instance.collection('rooms').document(pinid).snapshots(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
if ((snapshot.data['Votes'][0] + snapshot.data['Votes'][1]) >=
snapshot.data['joueurs']) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Results(),
));
}
}
return Center(
child: Text('VOUS AVEZ VOTE'),
);
},
),
);
}
That's because Flutter is triggering a frame build when you are trying to navigate to another screen, thus, that's not possible.
You can schedule a post frame callback so you can navigate as soon as Flutter is done with tree rebuilding for that widget.
import 'package:flutter/foundation.dart';
WidgetsBinding.instance.addPostFrameCallback(
(_) => Navigator.push(context,
MaterialPageRoute(
builder: (context) => Results(),
),
),
);
If navigation is the only thing happening on a button press, I wouldn't use a Bloc at all because Navigation is not business logic and should be done by the UI layer.
If you have business logic on a button press and need to navigate based on some dynamic information then I would do the navigation again in the presentation layer (widget) in response to a success state like below. You can also change navigation logic as per your requirement.
Widget loginButton(LoginBloc loginBloc) =>
StreamBuilder<List<UserLoginResultElement>>(
stream: loginBloc.loginStream,
builder:
(context, AsyncSnapshot<List<UserLoginResultElement>> snapshot) {
print(snapshot.connectionState);
Widget children;
if (snapshot.hasError) {
children = Padding(
padding: const EdgeInsets.only(top: 16),
child: Text('Error: ${snapshot.error}'),
);
} else {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
case ConnectionState.done:
case ConnectionState.active:
children = BlockButtonWidget(
text: Text(
"LOGIN",
style: TextStyle(color: Theme.of(context).primaryColor),
),
color: Theme.of(context).accentColor,
onPressed: () async {
try {
bloc.submit(_userNameController.value.text,
_passwordController.value.text, context);
} catch (ex) {
print(ex.toString());
}
},
);
break;
}
}
if (snapshot.data != null && snapshot.hasData) {
if (snapshot.data[0].code == "1") {
SchedulerBinding.instance.addPostFrameCallback((_) {
Navigator.pushReplacementNamed(context, "/HomeScreen");
});
} else {
print(Login Failed');
}
}
return children;
});

Flutter rendering list from firebase based on condition in dropdown menu

I'm trying to figure out how to render a list from a specific collection in firebase and to change that list when selecting options from dropdown menu. I could get the list rendered on 1 collection, but when I add my dropdown menu, with the default value being 'lost', nothing is displayed. Here's what I have so far that works, but not entirely what I want.
class _ListPageState extends State<ListPage>{
List<String> _type = ['lost', 'found'];
String _selectedView = 'lost';
//this getData pulls from 'lost' collection, since I set _selectedView to lost by default
Future getData() async{
var firestore = Firestore.instance;
QuerySnapshot qn = await firestore.collection(_selectedView).getDocuments();
return qn.documents;
}
navigateToDetail(DocumentSnapshot post){
Navigator.push(context, MaterialPageRoute(builder: (context) => DetailPage(post: post,)));
}
Widget _viewType() {
return new DropdownButtonFormField(
value: _selectedView,
onChanged: (newValue) {
setState(() {
_selectedView = newValue;
});
},
items: _type.map((view) {
return new DropdownMenuItem(
child: new Text(view),
value: view,
);
}).toList(),
);
}
#override
Widget build(BuildContext context){
return ListView(
children: <Widget>[
_viewType(),
FutureBuilder(//it's not rendering any of this when adding the dropdown above it
future: getData(),
builder: (_, snapshot){
if(snapshot.connectionState == ConnectionState.waiting){
return Center(
child: Text("Loading"),
);
}
else{
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, index){
return ListTile(
title: Text(snapshot.data[index].data["Title"]),
onTap: () => navigateToDetail(snapshot.data[index]),
);
});
}
}),]
);
}
}
Thanks in advance for any help.
Please let me know if there's any more code you'd like to see.
I this I have to wrap part of it with setState(), but I'm not quite sure where.
Thanks for the fast clarification.
What is happening here is that you have put a ListView inside a ListView. You should use a Column.
By default (as mentioned in the documentation):
The Column widget does not scroll (and in general it is considered an error to have more children in a Column than will fit in the available room). If you have a line of widgets and want them to be able to scroll if there is insufficient room, consider using a ListView.
In your case, you want to place a ListView that will overflow the Column that can't scroll. To avoid that, consider using an Expanded
to take the remaining space so that the height is somehow constrained and the ListView knows its limits and work properly.
class _ListPageState extends State<ListPage> {
List<String> _type = ['lost', 'found'];
String _selectedView = 'lost';
//this getData pulls from 'lost' collection, since I set _selectedView to lost by default
Future getData() async {
var firestore = Firestore.instance;
QuerySnapshot qn = await firestore.collection(_selectedView).getDocuments();
return qn.documents;
}
navigateToDetail(DocumentSnapshot post) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailPage(
post: post,
)));
}
Widget _viewType() {
return new DropdownButtonFormField(
value: _selectedView,
onChanged: (newValue) {
setState(() {
_selectedView = newValue;
});
},
items: _type.map((view) {
return new DropdownMenuItem(
child: new Text(view),
value: view,
);
}).toList(),
);
}
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
_viewType(),
Expanded(
child: FutureBuilder(
//it's not rendering any of this when adding the dropdown above it
future: getData(),
builder: (_, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Text("Loading"),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
return ListTile(
title: Text(snapshot.data[index].data["Title"]),
onTap: () => navigateToDetail(snapshot.data[index]),
);
},
);
}
},
),
),
],
);
}
}

Resources