数据视图有,布局视图消失
介绍 (Intro)
If I ask you to develop a page that fetches its information as soon as we open it, you’d probably be done in a couple of minutes. You have a variety of hooks to choose for doing the job. Maybe initState, didChangeDependencies with a control flag, your BLoC's constructor or anything similar, and they would all work just fine.
如果我要求您开发一个页面,以便在我们打开页面后立即获取其信息,则可能会在几分钟后完成。 您有多种选择可以完成工作。 也许是带有控制标志的initState , didChangeDependencies ,您的BLoC的构造函数或类似的东西,它们都可以正常工作。
But now, what if I ask you to re-fetch the same info whenever the page appears on screen instead of only when it is first opened?
但是现在,如果我要您在页面出现在屏幕上而不是仅在第一次打开页面时重新获取相同的信息怎么办?
每次页面出现在屏幕上? (Every Time the Page Appears on Screen?)
In other words: every time the page has the focus.
换句话说:每次页面都具有焦点。
That encompasses three scenarios:
这包括三种情况:
- When we first open it; 当我们第一次打开它时;
- When we come back to it after opening another page; 当我们打开另一页后回到它时;
- When we put the app in the background while the page was on screen, and then bring the app back to the foreground; 当我们在页面显示在屏幕上时将应用程序置于后台,然后将应用程序带回前台;
Native mobile developers acknowledge this as using the onResume or viewDidAppear callback, but in Flutter, there wasn't a dead-simple way to accomplish the same.
本机移动开发人员承认这是使用onResume或viewDidAppear回调,但是在Flutter中,并没有一种简单的方法来完成此操作。
Your first impulse will tell you to use the build method, but that’s a terrible idea because it runs anytime your widget needs to rebuild, and that happens quite a lot.
您的第一个冲动将告诉您使用build方法,但这是一个糟糕的主意,因为它可以在您的小部件需要重建的任何时候运行,并且这种情况经常发生。
Then, after spending some time at Google or StackOverflow, RouteObserver along with RouteAware widgets will pop at you. It's a way to register your widget to be notified whenever we push and pop back to its Route. Problems? It won't effortlessly work if you use nested Navigators. Think about it: if you use, for example, a bottom navigation structure, there are two ways in which your page can appear on screen:
然后,在Google或StackOverflow花了一些时间后, RouteObserver和RouteAware窗口小部件会弹出来。 这是一种注册小部件的方法,每当我们按下并弹出其Route时,便会收到通知。 问题? 如果您使用嵌套的Navigator ,它将无法轻松工作。 考虑一下:例如,如果使用底部导航结构 ,则可以通过两种方式将页面显示在屏幕上:
If we push or pop back to its
Route;如果我们推或弹出它的
Route;If we push or pop back to its “parent widget’s
Route“ (the page holding the bottom navigation menu);如果我们将其推回或弹出回到其“父小部件的
Route”(包含底部导航菜单的页面);
To cover the second case, we would have to do all the RouteAware set up on the parent widget as well and find a way to propagate the event down the tree. If it sounded like a lot of work, that's because it is! Also, it wouldn't cover the scenario in which we put the app in the background and then bring it to the foreground again, as the pushed route's remained the same.
为了解决第二种情况,我们还必须在父窗口小部件上进行所有RouteAware设置,并找到一种将事件传播到树上的方法。 如果听起来很麻烦,那是因为! 此外,它不会涵盖将应用程序置于后台然后再次将其置于前台的情况,因为所推送的路线保持不变。
Thankfully, some guys at Google (apparently not from the core Flutter team) provided us a package that gets us closer to what we want.
值得庆幸的是,Google的一些人(显然不是来自Flutter核心团队)为我们提供了一个使我们更接近所需内容的软件包。
VisibilityDetector软件包 (The VisibilityDetector Package)
A VisibilityDetector widget wraps an existing Flutter widget and fires a callback when the widget’s visibility changes.
VisibilityDetector小部件包装现有的Flutter小部件,并在小部件的可见性更改时触发回调。
It looks that now we have everything figured out, right?!
看来现在我们已经解决了所有问题,对吧?
Not yet! 😩
还没! 😩
The VisibilityDetector won't detect the case in which we bring the app back to the foreground while the widget was visible. Fortunately, Flutter does have an easy way for covering that: WidgetsBindingObserver. We just need to combine it with the VisibilityDetector.
VisibilityDetector不会检测到在可见小部件时将应用重新带回前台的情况。 幸运的是,Flutter 确实有一个简单的方法可以解决这一问题: WidgetsBindingObserver 。 我们只需要将其与VisibilityDetector结合即可。
FocusDetector软件包诞生了 (The FocusDetector Package Was Born)
https://pub.dev/packages/focus_detector
https://pub.dev/packages/focus_detector
You can depend on it or just copy-paste the below gist into your project. I strongly recommend the former, so that you get any bug fixes.
您可以依赖它,也可以将以下要点复制粘贴到您的项目中。 我强烈建议您使用前者,以便您修复所有错误。
library focus_detector;
import 'package:flutter/widgets.dart';
import 'package:visibility_detector/visibility_detector.dart';
/// Wrapper around Google's VisibilityDetector
/// for combining it with Flutter's WidgetsBindingObserver in order to achieve
/// Android's onResume/onPause and iOS's viewDidAppear/viewDidDisappear on
/// Flutter.
class FocusDetector extends StatefulWidget {
/// Constructor.
///
///
/// `key` is required to properly identify this widget; it must be unique
/// among all [FocusDetector] widgets.
const FocusDetector({
@required Key key,
@required this.child,
this.onFocusGained,
this.onFocusLost,
}) : assert(key != null),
assert(child != null),
super(key: key);
/// Called when the focus is obtained.
final VoidCallback onFocusGained;
/// Called when the focus is lost.
final VoidCallback onFocusLost;
final Widget child;
@override
_FocusDetectorState createState() => _FocusDetectorState();
}
class _FocusDetectorState extends State<FocusDetector>
with WidgetsBindingObserver {
bool _isVisible = false;
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// It only makes sense to report the focus change when the app's lifecycle
// state changes while this Widget was visible.
if (state == AppLifecycleState.resumed &&
_isVisible &&
widget.onFocusGained != null) {
widget.onFocusGained();
}
if (state == AppLifecycleState.paused &&
_isVisible &&
widget.onFocusLost != null) {
widget.onFocusLost();
}
}
@override
Widget build(BuildContext context) => VisibilityDetector(
key: widget.key,
onVisibilityChanged: (visibilityInfo) {
// In order to know if we're visible or not, we just need to make
// sure that our visible fraction is greater than zero.
_isVisible = visibilityInfo.visibleFraction > 0;
if (_isVisible && widget.onFocusGained != null) {
widget.onFocusGained();
}
if (!_isVisible && widget.onFocusLost != null) {
widget.onFocusLost();
}
},
child: widget.child,
);
@override
void initState() {
WidgetsBinding.instance.addObserver(this);
super.initState();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
}
用法 (Usage)
If you’ve followed my previous posts, you know that I have this Breaking Bapp project I like using for showcasing. It uses a simple master-detail pattern for displaying Breaking Bad ‘s info.
如果您关注了我以前的文章,那么您会知道我喜欢使用此Breaking Bapp项目进行展示。 它使用简单的主从模式显示Breaking Bad的信息。
From a product perspective, it isn’t the best use case for the FocusDetector. Re-fetching information every time the page gains the focus isn't useful at all for an app like this. It only consumes unnecessary bandwidth and makes the app slower.
从产品的角度来看,这不是FocusDetector的最佳用例。 每次页面获得焦点时重新获取信息对于这样的应用程序根本没有用。 它只会消耗不必要的带宽,并使应用变慢。
On the other hand, as far as the code goes, its simplicity is ideal for you to see the FocusDetector in action.
另一方面,就代码而言,其简单性非常适合您查看正在运行的FocusDetector 。
/// Fetches and displays a list of characters' summarized info.
class CharacterListPage extends StatefulWidget {
@override
_CharacterListPageState createState() => _CharacterListPageState();
}
class _CharacterListPageState extends State<CharacterListPage> {
Object _activeCallbackIdentity;
List<CharacterSummary> _characterSummaryList;
bool _isLoading = true;
bool _hasError = false;
// Vital for identifying our FocusDetector when a rebuild occurs.
final Key _focusDetectorKey = UniqueKey();
@override
Widget build(BuildContext context) => FocusDetector(
key: _focusDetectorKey,
onFocusGained: _fetchCharacterSummaryList,
onFocusLost: () {
print('CharacterListPage lost focus');
},
child: Scaffold(
appBar: AppBar(
title: const Text('Characters'),
),
body: ResponseView(
isLoading: _isLoading,
hasError: _hasError,
onTryAgainTap: _fetchCharacterSummaryList,
contentWidgetBuilder: (context) => ListView.builder(
itemCount: _characterSummaryList.length,
itemBuilder: (context, index) {
final character = _characterSummaryList[index];
return CharacterListItem(
character: character,
onTap: () {
// Detailed tutorial on this:
// https://edsonbueno.com/2020/02/26/spotless-routing-and-navigation-in-flutter/
Navigator.of(context).pushNamed(
RouteNameBuilder.characterById(
character.id,
),
);
},
);
},
),
),
),
);
@override
void dispose() {
_activeCallbackIdentity = null;
super.dispose();
}
Future<void> _fetchCharacterSummaryList() async {
setState(() {
_isLoading = true;
});
final callbackIdentity = Object();
_activeCallbackIdentity = callbackIdentity;
try {
final fetchedCharacterList = await DataSource.getCharacterList();
if (callbackIdentity == _activeCallbackIdentity) {
setState(() {
_characterSummaryList = fetchedCharacterList;
_isLoading = false;
_hasError = false;
});
}
} on Exception {
if (callbackIdentity == _activeCallbackIdentity) {
setState(() {
_hasError = true;
_isLoading = false;
});
}
}
}
}
That’s all! It couldn’t be simpler!
就这样! 这再简单不过了!
Previously, the above code was calling the _fetchCharacterSummaryList method on the initState callback. You can see the initial and final versions by checking out the focus-detector/set-state-initial and focus-detector/set-state-bloc-detector branches, respectively, of the GitHub Repository.
以前,以上代码是在initState回调上调用_fetchCharacterSummaryList方法。 您可以分别focus-detector/set-state-bloc-detector GitHub Repository的focus-detector/set-state-initial和focus-detector/set-state-bloc-detector分支来查看初始版本和最终版本。
奖金 (Bonus)
For an example using BLoCs, compare the focus-detector/bloc-initial and focus-detector/bloc-focus_detector branches.
对于使用BLoC的示例,请比较focus-detector/bloc-initial和focus-detector/bloc-focus_detector分支。
数据视图有,布局视图消失



所有评论(0)