[英]Flutter - Providers and Future calls, how to share the same instance?
I'm learning Flutter and there is something I cannot grasp my head around.我正在学习 Flutter 并且有些东西我无法掌握。 I implemented a Infinite scroll pagination, with a package ( infine_scroll_pagination
), it works fine, but the data this Package
is getting, comes from a Future
call, which takes data from the WEB
, and parses it in my Provider Class
. I implemented a Infinite scroll pagination, with a package ( infine_scroll_pagination
), it works fine, but the data this Package
is getting, comes from a Future
call, which takes data from the WEB
, and parses it in my Provider Class
.
My issue is, the data
that is loaded by the Infinite Scroll widget
, cannot be accessed, in its state
, anywhere else.我的问题是, Infinite Scroll widget
加载的data
无法在其state
中的其他任何地方访问。
Example: Let's take a contact list
, that loads 10 contacts at a time:示例:让我们获取一个contact list
,一次加载 10 个联系人:
class ContactsBody extends StatefulWidget {
@override
_ContactsBodyState createState() => _ContactsBodyState();
}
class _ContactsBodyState extends State<ContactsBody> {
static const _pageSize = 10;
final PagingController<int, Contact> pagingController =
PagingController(firstPageKey: 0);
@override
void initState() {
super.initState();
pagingController.addPageRequestListener((pageKey) {
_fetchPage(pageKey);
});
}
Future<void> _fetchPage(int pageKey) async {
try {
final newItems = await ContactsService().fetchContactsPaged(pageKey, _pageSize);
final isLastPage = newItems.length < _pageSize;
if (isLastPage) {
pagingController.appendLastPage(newItems.contacts);
} else {
final nextPageKey = pageKey + 1;
pagingController.appendPage(newItems.contacts, nextPageKey);
}
} catch (error) {
pagingController.error = error;
}
}
@override
Widget build(BuildContext context) {
return ContactsList(pagingController);
}
@override
void dispose() {
pagingController.dispose();
super.dispose();
}
So basically this Infinite Scroll package, will fetch my contacts, 10 at a time, and here my ContactsService
call:所以基本上这个无限滚动 package 会一次获取我的联系人,10 个,这里是我的ContactsService
调用:
Future<Contacts> fetchContactsPaged(int pageKey, int pageSize) async {
final response = await http.get(.....);
if (response.statusCode == 200) {
return Contacts.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load contacts');
}
}
And finally, as you can see here above, it initializes my Provider class
(Contacts), using its factory method, " fromJson()
", and returns the parsed data
.最后,正如您在上面看到的,它使用其工厂方法“ fromJson()
”初始化我的Provider class
(联系人),并返回parsed data
。
Now my Provider class
:现在我的Provider class
:
class Contacts extends ChangeNotifier {
List<Contact> _contacts = <Contact>[];
Contacts();
factory Contacts.fromJson(final Map<String, dynamic> json) {
final Contacts contacts = Contacts();
if (json['data'] != null) {
json['data'].forEach((contact) {
contacts.add(Contact.fromJson(contact));
});
}
return contacts;
}
void add(final Contact contact) {
this._contacts.add(contact);
this.notifyListeners();
}
The problem I'm having here is, when the Inifinite Scroll listView
is loaded, and for example I change the state
of a single contact (contacts can be set as favorite for example),我在这里遇到的问题是,当加载Inifinite Scroll listView
时,例如我更改了单个联系人的state
(例如,可以将联系人设置为收藏夹),
How can I access the SAME instanc
e of the Contacts() class
, that the FUTURE
call initialized, so that I can access the current state
of the data in that class?如何访问已初始化FUTURE
调用的Contacts() class
的SAME instanc
,以便我可以访问该 ZA2F2ED4F8EBC2CBB4C21A29D40AB6 中数据的current state
state?
Of course if I were to POST
my changes onto the API, and refetch the new values where I need them, I would get the updated state of my data, but I want to understand how to access the same instance here and make the current data available inside the app everywhere当然,如果我将我的更改发布到POST
,并在我需要的地方重新获取新值,我将获得更新后的 state 数据,但我想了解如何在此处访问同一个实例并制作当前数据在应用程序内随处可用
EDIT: I removed the original answer to give a better sample of what the OP wants to achieve.编辑:我删除了原始答案,以便更好地了解 OP 想要实现的目标。
I made a repo on GitHub to try to show you what you want to achieve: https://github.com/Kobatsu/stackoverflow_66578191我在 GitHub 上做了一个回购,试图向您展示您想要实现的目标: https://github.com/Kobatsu/stackoverflow_66578191
There are a few confusing things in your code:您的代码中有一些令人困惑的事情:
The repository results in the following:存储库产生以下结果:
When you update the list (by scrolling down), the yellow container is updated with the number of contacts and the number of favorites.当您更新列表(通过向下滚动)时,黄色容器会更新为联系人数量和收藏夹数量。 If you click on a Contact, it becomes a favorite and the yellow container is also updated.如果您单击联系人,它将成为收藏夹,并且黄色容器也会更新。
I commented the repository to explain you each part.我评论了存储库以向您解释每个部分。
Note: the Contacts class in your code became ContactProvider in mine.注意:您代码中的 Contacts class 在我的代码中变成了 ContactProvider。
The ContactsService class to make the API call: ContactsService class 拨打 API 电话:
class ContactsService {
static Future<List<Contact>> fetchContactsPaged(
int pageKey, int pageSize) async {
// Here, you should get your data from your API
// final response = await http.get(.....);
// if (response.statusCode == 200) {
// return Contacts.fromJson(jsonDecode(response.body));
// } else {
// throw Exception('Failed to load contacts');
// }
// I didn't do the backend part, so here is an example
// with what I understand you get from your API:
var responseBody =
"{\"data\":[{\"name\":\"John\", \"isFavorite\":false},{\"name\":\"Rose\", \"isFavorite\":false}]}";
Map<String, dynamic> decoded = json.decode(responseBody);
List<dynamic> contactsDynamic = decoded["data"];
List<Contact> listOfContacts =
contactsDynamic.map((c) => Contact.fromJson(c)).toList();
// you can return listOfContacts, for this example, I will add
// more Contacts for the Pagination plugin since my json only has 2 contacts
for (int i = pageKey + listOfContacts.length; i < pageKey + pageSize; i++) {
listOfContacts.add(Contact(name: "Name $i"));
}
return listOfContacts;
}
}
Usage of Provider:提供者的用法:
Consumer<ContactProvider>(
builder: (_, foo, __) => Container(
child: Text(
"${foo.contacts.length} contacts - ${foo.contacts.where((c) => c.isFavorite).length} favorites"),
padding: EdgeInsets.symmetric(
horizontal: 20, vertical: 10),
color: Colors.amber,
)),
Expanded(child: ContactsBody())
]),
)
Fetch page method in the ContactsBody class, where we add the contact to our ContactProvider: ContactsBody class 中的 Fetch page 方法,我们将联系人添加到我们的 ContactProvider 中:
Future<void> _fetchPage(int pageKey) async {
try {
// Note : no need to make a ContactsService, this can be a static method if you only need what's done in the fetchContactsPaged method
final newItems =
await ContactsService.fetchContactsPaged(pageKey, _pageSize);
final isLastPage = newItems.length < _pageSize;
if (isLastPage) {
_pagingController.appendLastPage(newItems);
} else {
final nextPageKey = pageKey + newItems.length;
_pagingController.appendPage(newItems, nextPageKey);
}
// Important : we add the contacts to our provider so we can get
// them in other parts of our app
context.read<ContactProvider>().addContacts(newItems);
} catch (error) {
print(error);
_pagingController.error = error;
}
}
ContactItem widget, in which we update the favorite statuts and notify the listeners: ContactItem 小部件,我们在其中更新收藏状态并通知听众:
class ContactItem extends StatefulWidget {
final Contact contact;
ContactItem({this.contact});
@override
_ContactItemState createState() => _ContactItemState();
}
class _ContactItemState extends State<ContactItem> {
@override
Widget build(BuildContext context) {
return InkWell(
child: Padding(child: Row(children: [
Expanded(child: Text(widget.contact.name)),
if (widget.contact.isFavorite) Icon(Icons.favorite)
]), padding: EdgeInsets.symmetric(vertical: 8, horizontal: 10),),
onTap: () {
// the below code updates the item
// BUT others parts of our app won't get updated because
// we are not notifying the listeners of our ContactProvider !
setState(() {
widget.contact.isFavorite = !widget.contact.isFavorite;
});
// To update other parts, we need to use the provider
context.read<ContactProvider>().notifyContactUpdated(widget.contact);
});
}
}
And the ContactProvider:和 ContactProvider:
class ContactProvider extends ChangeNotifier {
final List<Contact> _contacts = [];
List<Contact> get contacts => _contacts;
void addContacts(List<Contact> newContacts) {
_contacts.addAll(newContacts);
notifyListeners();
}
void notifyContactUpdated(Contact contact) {
// You might want to update the contact in your database,
// send it to your backend, etc...
// Here we don't have these so we just notify our listeners :
notifyListeners();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.