Ui is updating only for last stream in flutter - flutter

I am making a sms_app that can get data from the List of Objects when I press the button send the sms.Objects have a method which returns a stream. I am iterating through the data with ListViewbuilder and listening to stream via StreamViewBuilder. All the Object Streams are performing the function of sending the message. If i press the first send button ,then wait,press the second button and wait, it updates the UI accordingly.
But
UI is being updated for the last Stream. If I press the button one after another button without waiting. What am I doing wrong>.
Here is the Video
import 'package:flutter/material.dart';
import 'package:sms_maintained/sms.dart';
class SendSmsScreen extends StatelessWidget {
final SmsSender sender = SmsSender();
final SmsMessage message = SmsMessage('03009640742', '_body');
final List<SmsMessage> smsList = [
SmsMessage('03009750742', 'Random'),
SmsMessage('03008750742', 'Kaleem'),
SmsMessage('03056750742', 'Shahryar'),
SmsMessage('03127750742', 'Shahryar Zong')
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: ListView.builder(
itemCount: smsList.length,
itemBuilder: (context, index) {
return SingleChildScrollView(
child: Column(
children: [
IconButton(
icon: Icon(Icons.send),
onPressed: () async {
await sender.sendSms(smsList[index]);
},
),
StreamBuilder<SmsMessageState>(
key: GlobalKey(debugLabel: 'String $index'),
// initialData: SmsMessageState.None,
builder: (context, snapshot) {
if (snapshot.data == SmsMessageState.Sent) {
return Text('Message Sent');
}
if (snapshot.data == SmsMessageState.Delivered) {
return Text('Message Delivered');
}
if (snapshot.data == SmsMessageState.Sending) {
return Text('Sending');
}
if (snapshot.data == SmsMessageState.Fail)
return Text('Sending Failed');
return Text('Error');
},
stream: smsList[index].onStateChanged,
),
],
),
);
},
));
}
}

I'm assuming the UI doesn't update properly if pressing the button too quickly.
You can disable the button (example below) until the message is delivered you just need to set your button to be a child of the StreamBuilder.
onPressed: snapshot.data == SmsMessageState.Sending ? null : () async {
await sender.sendSms(smsList[index]);
}

That's because they are all executing the same method. When you do multiple executions in quick succession, last one stops the execution of previous. You'll have to find a way to queue them as they are executed and only do the next one when when the previous one is finished.

Related

Flutter stream deletion issue

I am working on Flutter application that uses Firestore. I have shown my documents in app with list view. I can update the documents and it appears immediately in app thanks to Flutter stream. However, I'm having an issue when I'm deleting a document. Seems deletion is working fine in reality, but the display in app is showing wrong information. For example, I delete a document at index 1, but always the document at last index is removed. Seems the event coming from FireStore stream just updating number of documents in stream, the list view is showing the information through another widget (like customer List tile) the information for each index is not updated correctly. Below is my code:
class _BudgetSummaryState extends State<BudgetSummary> {
Stream<QuerySnapshot> getSummaries() => FirebaseFirestore.instance
.collection('Users')
.doc(FirebaseAuth.instance.currentUser!.phoneNumber)
.collection('UserDBs')
.snapshots();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar('Summary'),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {
Navigator.of(context).pushNamed('/Update_Edit_Screens/AddNewBudget');
},
label: const Text('Add new'),
icon: const Icon(Icons.add),
),
body: SafeArea(
child: StreamBuilder<QuerySnapshot>(
stream: getSummaries(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Center(
child: Text('Something went wrong, please try again later'),
);
}
if (snapshot.hasData) {
var data = snapshot.data;
if (data == null) {
return const Center(
child: Text('Add you first budget/expense tracker'),
);
} else {
return ListView.builder(
itemCount: data.docs.length,
itemBuilder: ((context, index) {
Color col =
index % 2 == 0 ? Colors.lightBlue : Colors.lime;
return SummaryWidget(data.docs[index], col);
}));
}
}
I did a workaround by reloading the whole page, that is rebuilding the complete route. But somehow I feel it kills the purpose of using stream. Please advise if I'm missing something?
Classic problem of data removal in Flutter.
You need to provide Key for each list item. You can use ValueKey with can take some unique id for each list item. Something like
return SummaryWidget(key:ValueKey(data.docs[index].id), data.docs[index], col);
Let me know if you want to know the reasoning, I will update here.

Using GetX in a FutureBuilder to build a list - the UI is not updated

I'm creating a todo list (sort of) app.
I have a view where I use a FutureBuilder, it calls a function to fetch the articles from the SQLite db and show as Card.
I have a getx_controller.dart which contains the list as observable:
class Controller extends GetxController {
// this is the list of items
var itemsList = <Item>[].obs;
}
and I have a items_controller.dart
// function to delete an item based on item id
void deleteItem(id) {
final databaseHelper = DatabaseHelper();
// remove item at item.id position
databaseHelper.deleteItem(tableItems, id);
print('delete item with id $id');
this.loadAllItems();
}
the loadAllItems is a function that queries the DB
And finally, the list_builder.dart which contains the FutureBuilder
final itemController = Get.put(ItemsController());
#override
Widget build(BuildContext context) {
return FutureBuilder<List<Item>>(
future: itemController.loadAllItems(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasData) {
print(snapshot.data.toString());
return Obx(() => ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return Slidable(
actionExtentRatio: 0.25,
actionPane: SlidableDrawerActionPane(),
child: _itemCard(index, snapshot.data![index]),
actions: <Widget>[
IconSlideAction(
caption: 'Elimina',
color: Colors.red,
icon: Icons.delete,
onTap: () {
itemController.deleteItem(snapshot.data![index].id);
itemController.loadAllItems();
}),
],
secondaryActions: <Widget>[
IconSlideAction(
caption: 'Modifica',
color: Colors.blue,
icon: Icons.edit,
onTap: () {},
),
],
);
}));
} else {
return Container(
child: Text('Loading'),
);
}
});
// });
}
My issue is that when I tap on "Elimina" (or I create a new item, same procedure), the ListBuilder doesn't refresh the list on the screen, despite of having the itemsList recreated (using getxController.itemsList = RxList.generate(...)) and observable.
You don't need to use FutureBuilder when using observables. This is redundant and makes your code complicated.
Instead you should assign the awaited Future (the actual data/items) to your observable list (itemList). And your UI should update automagically.
So your controller should look something like this:
class Controller extends GetxController {
// this is the list of items
var itemsList = <Item>[].obs;
#override
onInit()async{
await loadAllItems();
}
loadAllItems()async{
var databaseResponse= await dbHelper.getAll();
itemList.assignAll(databaseResponse);
}
}
And your UI build method should just return the observing (Obx) ListView.builder like the following and you are done:
#override
Widget build(BuildContext context){
return Obx(() => ListView.builder(
itemCount: controller.itemList.length,
itemBuilder: (context, index) {
var item = comtroller.itemList[index]; // use this item to build your list item
return Slidable(

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);
}
}
}

How to retrieve Firestore data using 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.

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,)
));},