How to retrieve Firestore data using flutter - flutter

I was now trying for days to retrieve my firestore values, but no luck so posting it here.
I have a Firestore database and some data. I want to retrieve this with the help of Flutter.
This is what I have been doing.
So I have a Flutter screen where it shows a simple 3-dot dropdown in the AppBar.
It has two options: edit and cancel.
What I want is, when I press edit, it should open a new screen and should pass the data that I retrieved from firestore.
This is where I have edit and cancel dropdown (3 dots) and calling the a function (to retrieve data and open the new screen).
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(widget.news.headline.toUpperCase()),
actions: <Widget>[
PopupMenuButton<String>(
onSelected: (value) {
_open_edit_or_delete(value); // caling the function here
},
itemBuilder: (BuildContext context) {
return {'Edit', 'Delete'}.map((String choice) {
return PopupMenuItem<String>(
value: choice,
child: Text(choice),
);
}).toList();
},
),
],
),
body: _get_particular_news(widget.news),
);
}
and this is the open_edit_or_delete function it is calling. But it doesn't open up (navigate) to the screen I am calling.
open_edit_or_delete(String selectedOption) {
News news;
Visibility(
visible: false,
child: StreamBuilder(
stream: FireStoreServiceApi().getNews(),
builder: (BuildContext context, AsyncSnapshot<List<News>> snapshot) {
if (snapshot.hasError || !snapshot.hasData) {
Navigator.push(
context, MaterialPageRoute(builder: (_) => FirstScreen(news:news)));
return null;
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
news = snapshot.data[index];
},
);
}
},
));
}
And in case you need the FireStoreServiceApi().getNews(), here it is as well.
// get the news
Stream<List<News>> getNews() {
return _db.collection("news").snapshots().map(
(snapshot) => snapshot.documents
.map((doc) => News.fromMap(doc.data, doc.documentID))
.toList(),
) ;
}
Can someone please help me?

You are not passing data correctly to your fromMap method.
You can access data using doc.data['']
If you have data and documentID property in it then following will work.
News.fromMap(doc.data.data, doc.data.documentID))
I don't know your fromMap method and i also don't what your snapshot contains, if this did not work for you then add them too.

Related

Flutter: BloC: SubBloC doesn't change when reordering list

I seem to have a wrong thinking when using a listview with BloC.
I have a listview populated by a BloC (dataBloc) and this list is ordered by a ViewBloc.
When I tap on the item, a SubDataBloc is updated and the result displayed in the trailing of the list tile
dataBloc/viewBloc:
ListTileA - SubdataBlocA
ListTileB - SubDataBlocB
ListTileC - SubDataBlocC
When I reorder the list - only the ListTiles are reordered, but not the SubdataBloc results
video:
https://gitlab.com/bridystone/bloc_test/-/blob/main/BloC-ListTile.mov
the whole example is here:
https://gitlab.com/bridystone/bloc_test
any idea, on how to make this happen?
ListView.builder
body: BlocBuilder<ViewBloc, ViewState>(
builder: (context, state) {
if (state is ViewInitial) {
return CircularProgressIndicator();
} else if (state is ViewReadyForUI) {
return ListView.builder(
itemCount: state.sortedData.length,
itemBuilder: (context, index) => BlocProvider(
create: (context) => SubDataBloc(),
child: MyTile(
dataItem: state.sortedData[index],
),
),
);
}
return Text('should not happen');
},
),
ListTile:
Widget build(BuildContext context) {
//BlocProvider.of<SubDataBloc>(context).add(SubDataRequest(dataItem.id));
return BlocBuilder<SubDataBloc, SubDataState>(
builder: (context, state) {
return ListTile(
leading: Text(dataItem.id.toString()),
title: Text(dataItem.text),
trailing: (state is SubDataReceived)
? Text('items: ${state.subdata.length}')
: (state is SubDataUpdating)
? Text('${state.percent}')
: Text('initial'),
onTap: () => BlocProvider.of<SubDataBloc>(context)
.add(SubDataRequest(dataItem.id)),
);
},
);
}
I've received a comment from Github/Bloc_library, which brought me to a solution.
I've transferred the SubdataBloc to the dataModel of the MainBloc.
So for each data, a corresponding SubBloc is stored.
I've now added the subDataBloc to the DataModel
class BlocModel {
final Model model;
SubDataBloc subDataBloc;
BlocModel(this.model, this.subDataBloc);
}
and added the BloC during generation to the Model
var modelData = List<BlocModel>.generate(
event.requestId,
(index) => BlocModel(
Model(Random().nextInt(event.requestId), "BLABLABLA $index"),
SubDataBloc())); // <-- added here
then I could just add the subbloc to the BlocBuilder with the bloc attribute
return BlocBuilder<SubDataBloc, SubDataState>(
bloc: dataItem.subDataBloc, //<-- using the data model-BloC
builder: (context, state) {
return ListTile(
leading: Text(dataItem.model.id.toString()),
title: Text(dataItem.model.text),
trailing: (state is SubDataReceived)
? Text('items: ${state.subdata.length}')
: (state is SubDataUpdating)
? Text('${state.percent}')
: Text('initial'),
onTap: () =>
dataItem.subDataBloc.add(SubDataRequest(dataItem.model.id)));
},
);
And now it is working as intended.

When to create new bloc?

I'm still learning bloc patter. I created two pages, ViewPage and DetailsPage using a single bloc.
This is my bloc:
getRecordEvent
deleteRecordEvent
LoadedState
LoadedErrorState
DeletedState
DeletedErrorState
The view page will only build a widget with list of records on a LoadedState. When the user taps any record, It will push the Details page and displays detailed record with a delete button. When user press the delete button, I listen to the DeletedState and call the getRecord event to populate the view page again with the updated record.
Its all working but my problem is when I encountered an error while deleting record. When the state is DeleteErrorState, my view page becomes empty since I don't call getRecord there because the error could be internet connection and two error dialog will be shown. One for the DeletedErrorState and LoadedErrorState.
I know this is the default behavior of bloc. Do I have to create a separate bloc with only deleteRecordEvent? And also if I create a new page for adding record, will this also be a separate bloc?
UPDATE:
This is a sample of ViewPage. The DetailsPage will only call the deleteRecordEvent once the button was pressed.
ViewPage.dart
void getRecord() {
BlocProvider.of<RecordBloc>(context).add(
getRecordEvent());
}
#override
Widget build(BuildContext context) {
return
Scaffold(
body: buildBody(),
),
);
}
buildBody() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: BlocConsumer<RecordBloc, RecordState>(
listener: (context, state) {
if (state is LoadedErrorState) {
showDialog(
barrierDismissible: false,
context: context,
builder: (_) {
return (WillPopScope(
onWillPop: () async => false,
child: ErrorDialog(
failure: state.failure,
)));
});
} else if (state is DeletedState) {
Navigator.pop(context);
getRecord();
} else if (state is DeletedErrorState) {
Navigator.pop(context);
showDialog(
barrierDismissible: false,
context: context,
builder: (_) {
return (WillPopScope(
onWillPop: () async => false,
child: ErrorDialog(
failure: state.failure,
)));
});
}
},
builder: (context, state) {
if (state is LoadedState) {
return Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
state.records.length <= 0
? noRecordWidget()
: Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: state.records.length,
itemBuilder: (context, index) {
return Card(
child: Padding(
padding: EdgeInsets.symmetric(
vertical: Sizes.s8),
child: ListTile(
title: Text(state.records[index].Name),
subtitle: state.records[index].date,
onTap: () {
showDialog(
barrierDismissible: false,
context: context,
builder: (_) {
return BlocProvider<RecordBloc>.value(
value: BlocProvider.of<RecordBloc>(context),
child: WillPopScope(
onWillPop: () async => false,
child:
DetailsPage(record:state.records[index]),
));
});
},
),
));
}),
),
],
),
);
}
return (Container());
},
),
),
);
}
About bloc
As a general rule of thumb, you need one bloc per ui. Of course, this is not always the case, as it depends on a few factors, the most important of which is how many events are you handling in your ui. For your case, where there is a ui that holds a list of items into an item-details ui, I would create two blocs. One will only handle loading items (ItemsBloc for instance), the other will handle actions to a single item (SingleItemBloc). I might only use the delete event for now, but as the app grows, I will be adding more events. This all facilitates the Separation of Concerns concept.
Applying that to your case, the SingleItemBloc will handle deleting, modifying, subscribing, etc to a single item, while ItemsBloc will handle loading the items from the different repositories (local/remote).
Since I don't have the code for your bloc I can't offer any modifications.
Solution specific to your case
It seems that you're losing the last version of your list of items every time a new state is emitted. You should keep a local copy of the last list you acquired from your repositories. In case there is an error, you just use that list; if not just save the new list as the last list you had.
class MyBloc extends Bloc<Event, State> {
.....
List<Item> _lastAcquiredList = [];
Stream<State> mapEventToState(Event event) async* {
try {
....
if(event is GetItemsEvent) {
var newList = _getItemsFromRepository();
yield LoadedState(newList);
_lastAcquiredList = newList;
}
....
} catch(err) {
yield ErrorState(items: _lastAcquiredItems);
}
}
}

Refresh swipe up to refresh widget flutter

I have an app that gets some data from firebase and than calls a class to display a widget based on the data from firebase. I tried adding a swipe up refresh but i have no idea where to put it and what to to call on refresh. I was trying it using the RefreshIndicator.
Here i will put my code in which it calls the database(firebase) and than creates an widget for each event in the database.
If you need any more information, please feel free to comment. Thank you so much for the help!
FutureBuilder(
future: databaseReference.once(),
builder: (context, AsyncSnapshot<DataSnapshot> snapshot) {
List lists = [];
if (snapshot.hasData) {
lists.clear();
Map<dynamic, dynamic> values = snapshot.data.value;
values.forEach((key, values) {
lists.add(values);
});
return new ListView.builder(
primary: false,
padding: EdgeInsets.only(left:12.0,right:12,bottom: 15,),
shrinkWrap: true,
itemCount: lists.length,
itemBuilder: (BuildContext context, int index) {
if(lists[index]["Status"]== "Active"){;
return Container(
child:EvendWidget(lists[index]["EventImage"],
Text(lists[index]["EventName"]).data,
Text(lists[index]["EventLocation"]+ ", "+lists[index]["EventCounty"] ).data,
Text(lists[index]["Date"]+ ", "+lists[index]["Time"]+ " - "+lists[index]["Time"]).data,
Text(lists[index]["Duration"]+ " H").data,
Text(lists[index]["Genre"]).data,
Text(lists[index]["Price"]).data,false));}else{return SizedBox.shrink(); };
});
}
return Container(
margin: const EdgeInsets.only(top: 300),
child:CircularProgressIndicator());
}),
Do something like this..
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: RefreshIndicator(
onRefresh: () async {
//write your code here to update the list*********
},
child: ListView.builder(
itemCount: 100,
itemBuilder: (BuildContext context, int index) {
return Text('Line $index');
}
)
),
);
}
}
You can try with below lines may be it will work for you
return RefreshIndicator(
color: Colors.blue,
onRefresh: () {
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (_) => HomePage()));
},
child: ListView.builder(
....
));

How to handle rebuild of graphql query when return to the page (Flutter)?

I am building ListView from data acquired using graphql api.
I am using flutter_graphql package to handle my request
Here is snippet of builder
build(BuildContext context){
return Query(
options: QueryOptions(
documentNode: gql(readRepositories),
variables: {'nRepositories': 50},
),
builder: (QueryResult result, { VoidCallback refetch, FetchMore fetchMore }) {
if (result.hasException) {
return Text(result.exception.toString());
}
if (result.loading) {
return CircularProgressIndicator();
}
repositories = result.data['viewer']['repositories']['nodes'];
return ListView.builder(
controller: repositoriesController,
itemCount: repositories.length,
itemBuilder: (context, index) {
final repository = repositories[index];
return ListTile(
leading: Icon(Icons.flight_land),
title: Text(repository['name']),
onTap: () {
Navigator.of(context).push(MaterialPageRoute( builder: (context) => RepositoryDetail(repository: repository,)));
}
)
});
},
);
}
my issue here is that, after user move to detail page. then when user click backButton this build will rebuild and create new request to api.
Notes:
There are filters will call this widget and rebuild it
There is pagination on scroll
How to handle this scenario?

Pass data from class to class - Flutter

I have a List Builder that creates a list based off of the documents listed in Firestore. I am trying to take the value generated from a Firestore snapshot and pass it out of the class to a variable that is updated every time the user clicks on a different entry from the List Builder.
Here is the class making the Firestore interaction and returning the ListBuilder:
class DeviceBuilderListState extends State<DeviceBuilderList> {
final flutterWebviewPlugin = new FlutterWebviewPlugin();
#override
void initState() {
super.initState();
// Listen for our auth event (on reload or start)
// Go to our device page once logged in
_auth.onAuthStateChanged
.where((user) {
new MaterialPageRoute(builder: (context) => new DeviceScreen());
});
// Give the navigation animations, etc, some time to finish
new Future.delayed(new Duration(seconds: 1))
.then((_) => signInWithGoogle());
}
void setLoggedIn() {
_auth.onAuthStateChanged
.where((user) {
Navigator.of(context).pushNamed('/');
});
}
#override
Widget build(BuildContext context) {
return new FutureBuilder<FirebaseUser>(
future: FirebaseAuth.instance.currentUser(),
builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot) {
if (snapshot.data != null)
return new StreamBuilder(
stream: Firestore.instance
.collection('users')
.document(snapshot.data.uid)
.collection('devices')
.snapshots,
builder: (context, snapshot) {
if (!snapshot.hasData)
return new Container();
return new Container(
margin: const EdgeInsets.symmetric(vertical: 10.0),
child: new ListView.builder(
itemCount: snapshot.data.documents.length,
padding: const EdgeInsets.all(10.0),
itemBuilder: (context, index) {
DocumentSnapshot ds =
snapshot.data.documents[index];
return new Card(
child: new GestureDetector(
onTap: () {
var initialStateLink = "${ds['name']}";
Navigator.of(context).pushNamed("/widget");
},
child: new Text(
" ${ds['name']}",
style: new TextStyle(fontSize: 48.0),
),
));
}),
);
},
);
else return new Container();
}
);}
}
Then I want to send the var initialStateLink to a different function in the same dart file:
Future<String> initialStateUrl() async {
final FirebaseUser currentUser = await _auth.currentUser();
Firestore.instance.collection('users')
.document(currentUser.uid).collection('devices').document(initialStateLink).get()
.then((docSnap) {
var initialStateLink = ['initialStateLink'];
return initialStateLink.toString();
});
return initialStateUrl().toString();
}
So that it returns me the proper String. I am at a complete loss on how to do this and I was unable to find another question that answered this. Thanks for the ideas.
You can use Navigator.push(Route route) instead of Navigator.pushNamed(String routeName)
And I don't encourage you to place navigation code deeply inside the widget tree, it's hard to maintain your logic of application flow because you end up with many pieces of navigation code in many classes. My solution is to place navigation code in one place (one class). Let's call it AppRoute, it looks like:
class AppRoute {
static Function(BuildContext, String) onInitialStateLinkSelected =
(context, item) =>
Navigator.of(context).push(
new MaterialPageRoute(builder: (context) {
return new NewScreen(initialStateLink: initialStateLink);
}
));
}
and replace your code in onTap:
onTap: () {
var initialStateLink = "${ds['name']}";
AppRoute.onInitialStateLinkSelected(context, initialStateLink);
}
Now, you not only can pass data from class to another class but also can control your application flow in ease (just look at AppRoute class)
Just make initialStateLink variable Global and send it as an argument to the another class like below,
a) Specify route as follows
'/widget' : (Buildcontext context) => new Anotherscreen(initialStateLink)
b) Navigate to the Anotherscreen()
c) Then the Anotherscreen () will be like this,
class Anotherscreen () extends StatelessWidget {
var initialStateLink;
Anotherscreen (this.initialStateLink);
......
}
I ended up finding a different solution that solved the problem (kind of by skirting the actual issue).
A MaterialPageRoute allows you to build a new widget in place while sending in arguments. So this made it so I didn't have to send any data outside of the class, here is my code:
return new Card(
child: new GestureDetector(
onTap: () {
Navigator.push(context,
new MaterialPageRoute(
builder: (BuildContext context) => new WebviewScaffold(
url: ds['initialStateLink'],
appBar: new AppBar(
title: new Text("Your Device: "+'${ds['name']}'),
),
withZoom: true,
withLocalStorage: true,)
));},