flutter有状态组件_Flutter的有状态小工具备忘单

flutter有状态组件

Instead of looking at something specific, let’s take a step back today and revert to one of the basics in Flutter. A brief overview of Stateful widgets in Flutter!

让我们今天退后一步,回到Flutter的基本知识之一,而不是看特定的东西。 Flutter中的有状态小部件的简要概述!

无状态与有状态 (Stateless vs. Stateful)

Before we take a look at Stateful widgets, we have to take a look at its counterpart: the Stateless widget. The naming should already give most of it away, but how does it look in practice?

在查看有状态窗口小部件之前,我们必须先看一下其对应对象:无状态窗口小部件。 命名应该已经放弃了大部分内容,但实际上它看起来如何?

Stateless widgets are, yes, stateless. You basically draw your widget once, and that’s it. It’s not made to change in any way, but rather just simply show how you defined it. Default examples of a Stateless widget could be Text or Container.

无状态小部件是无状态的。 您基本上只绘制一次小部件,仅此而已。 它不会以任何方式进行更改,而只是简单地显示您如何定义它。 无状态窗口小部件的默认示例可以是TextContainer

Stateful widgets, however, are dynamic. In short, this means that the widget might contain a property that can change, triggering your UI (widget) to update. Let’s take a checkbox, for example, containing 2 states: true or false/checked or unchecked. We’ll keep track of its state in a property: isChecked. Let’s assume the checkbox starts off in the unchecked state. By tapping it, we’ll update the isChecked property and update the UI accordingly. Since the isChecked property can change and the UI changes with it, the widget is dynamic, hence: Stateful!

但是,有状态小部件是动态的。 简而言之,这意味着小部件可能包含可以更改的属性,从而触发您的UI(小部件)更新。 让我们以一个包含2种状态的复选框为例:true或false /选中或未选中。 我们将在属性isChecked跟踪其状态。 假设复选框以未选中状态开始。 通过点击它,我们将更新isChecked属性并相应地更新UI。 由于isChecked属性可以更改并且UI随之更改,因此该小部件是动态的,因此:有状态!

Since Stateful widgets are dynamic, they’re more expensive to use as opposed to Stateless widgets. Always take this into account when wanting to convert a Stateless widget to a Stateful one!

由于有状态小部件是动态的,因此与无状态小部件相比,它们的使用成本更高。 想要将无状态小部件转换为有状态小部件时,请务必考虑到这一点!

创建一个有状态的小部件 (Creating a Stateful widget)

Unlike a Stateless widget, creating a Stateful widget requires 2 classes: the widget itself and its State. The widget itself won’t do much apart from actually creating the state through createState(). You could initialize some properties through the constructor, but most work will be done in the State class. The dynamic properties we described earlier will be put and updated here for example, but most importantly: the State class is where we actually build our widget tree.

与无状态窗口小部件不同,创建有状态窗口小部件需要2个类:窗口小部件本身及其状态。 小部件本身除了通过createState()实际创建状态外不会做很多事情。 您可以通过构造函数初始化一些属性,但是大多数工作将在State类中完成。 例如,我们前面将介绍的动态属性将在此处放置和更新,但最重要的是:State类是我们实际构建窗口小部件树的位置。

Let’s have a quick look at the bare minimum:

让我们快速浏览一下最低要求:

class MyStatefulWidget extends StatefulWidget {
  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}


class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

This is all it takes to get your Stateful widget started!

这就是启动您的有状态窗口小部件的全部步骤!

Tip: when creating a new class, just type stful and press tab to create the bare minimum of a Stateful widget. Already have a Stateless widget and want to convert it to a Stateful one? Just click your Stateless widget class and press alt + Enter on AS or ctrl + . on VS code to get an option to convert it to a Stateful widget!

提示:创建新类时,只需键入stful并按tab即可创建Stateful小部件的最低要求。 已经拥有一个无状态小部件,并希望将其转换为有状态小部件? 只需单击您的无状态窗口小部件类,然后按alt + Enter或按ctrl + . 在VS代码上获得将其转换为有状态小部件的选项!

更新您的UI (Updating your UI)

Cool, so now that we know that a Stateful widget is dynamic: how do we actually update the UI of a Stateful widget? 🤔 Let’s take the toggle we described earlier: nothing’s holding you back to simply update its property.

太酷了,现在我们知道有状态窗口小部件是动态的:我们实际上如何更新有状态窗口小部件的UI? 🤔让我们进行一下前面所述的切换:没有什么阻碍您简单地更新其属性。

isChecked = true;

Done! Not really though, because the UI doesn’t match the property anymore 🤔

做完了! 其实不是,因为UI不再与该属性匹配🤔

To update the UI, we need to trigger it ourselves when changing the property. To do this, we call the setState method:

要更新UI,我们需要在更改属性时自行触发它。 为此,我们调用setState方法:

setState({
isChecked = true;
});

As you can see, we now update the property inside the callback parameter. setState is called to tell the framework that the state has changed, and everything we’d like to change should be done inside that callback.

如您所见,我们现在更新callback参数中的属性。 调用setState告诉框架状态已更改,我们要更改的所有操作都应在该回调内完成。

生命周期 (Lifecycle)

A few methods can be overridden to hook into the lifecycle of a Stateful widget’s state. Let’s have a quick look to understand what to do where exactly.

可以重写一些方法来陷入有状态小部件状态的生命周期。 让我们快速看一下到底该怎么做。

initState() (initState( ))

As the naming suggests, this method is called when the widget’s state is initialized. It’s called just once and can be used for initializing properties that might rely on context or the state’s widget for example.

顾名思义,该方法在小部件的状态初始化时调用。 它仅被调用一次,可用于初始化可能依赖于context或状态widget属性。

didChangeDependencies() (didChangeDependencies( ))

This method is called right after initState and is triggered by dependency changes. This means data changed that could potentially require a UI update. It might be an InheritedWidget higher up the tree, but the system’s locale can also be a good example. You might not see this a lot in practice though since the build method is called after this and could also be used.

此方法在initState之后initState ,并由依赖项更改触发。 这意味着更改的数据可能需要更新UI。 它可能是树上方的InheritedWidget ,但系统的语言环境也是一个很好的例子。 尽管实际上在build之后会调用build方法,但实际上也可能会用到它,因此在实践中您可能看不到很多。

build(BuildContext上下文) (build(BuildContext context))

This is where we describe our UI. We’ll return our widget tree here.

这是我们描述UI的地方。 我们将在这里返回小部件树。

didUpdateWidget(Widget oldWidget) (didUpdateWidget(Widget oldWidget))

If our widget changes and is of the same runtimeType (and has the same key), this method is being called. We also receive the old widget here so we can compare it with the new widget if needed. The build method is being called after this method.

如果我们的窗口小部件发生更改并且具有相同的runtimeType (并且具有相同的键),则将调用此方法。 我们还会在此处收到旧的小部件,因此可以根据需要将其与新的小部件进行比较。 在此方法之后将调用build方法。

停用() (deactivate( ))

Deactivate is rarely used to be fair. It is called when state is removed from the tree, but it might be reinserted before the current frame change is finished. This method exists basically because State objects can be moved from one point in a tree to another.

停用很少是公平的。 当从树中删除状态时调用它,但是可能会在当前帧更改完成之前重新插入状态。 之所以存在此方法,是因为状态对象可以从树中的一个点移动到另一点。

处置() (dispose( ))

When the widget’s state is destroyed, dispose is being called. This is a good moment to close any streams or call dispose on things like Text editing controllers or focus nodes.

当小部件的状态被破坏时, dispose调用dispose 。 这是关闭任何流或在诸如文本编辑控制器或焦点节点之类的对象上进行调用处置的好时机。

性能 (Performance)

One thing has to be said: Stateful widgets are heavier than Stateless widgets. Even though you’ll probably start to worry about performance once you encounter issues, there are some things you can take into account from the get-go.

必须说一件事:有状态小部件比无状态小部件重。 即使一旦遇到问题,您可能会开始担心性能,但是从一开始就可以考虑一些因素。

使状态小部件保持较小 (Keep Stateful widgets small)

Calling setState on a Stateful widget triggers a (re)build of the widget tree. Try to make your Stateful widget as small as possible, so that it (almost) only contains the UI that actually needs to update.

在有状态窗口小部件上调用setState会触发(重新)构建窗口小部件树。 尝试使您的有状态小部件尽可能小,以使其(几乎)仅包含实际需要更新的UI。

使用常数 (Use constants)

If your Stateful widget contains widgets that don’t need to be rebuilt: try telling the framework! Some widgets have const constructors, meaning you can define them as constants in the widget tree. By doing so, the framework makes sure these widgets won’t be rebuilt when calling setState for example!

如果您的有状态窗口小部件包含不需要重建的窗口小部件,请尝试告诉框架! 一些小部件具有const构造函数,这意味着您可以在小部件树中将它们定义为常量。 这样,框架可以确保在调用setState时不会重建这些小部件!

不要过度使用构建方法 (Don’t overuse the build method)

It can be tempting to do stuff in the build method before actually building the widget tree, but keep in mind this method is called on every (re)build. This means that if you’re initializing stuff or doing some heavy calculations, this is being done every time. Try to make use of the other methods (like initState) or use flags to only do stuff only when necessary.

在实际构建窗口小部件树之前,可能会尝试在build方法中进行操作,但是请记住,在每次 (重新)构建时都会调用此方法。 这意味着,如果您要初始化东西或进行大量计算,那么每次都会这样做。 尝试利用其他方法(例如initState )或使用标志仅在必要时进行操作。

仅在需要时重建 (Only rebuild when needed)

It’s easy to call setState when something might’ve changed, but it’s not necessary to do so if nothing did right? Do some checks beforehand, check if properties changed (or need changing), and only call setState when you actually need it. No need to update the UI if it stays the same!

可能发生某些更改的情况下调用setState很容易,但是如果没有做对的事就没有必要这样做吗? 事先进行一些检查,检查属性是否已更改(或需要更改),仅在实际需要时才调用setState 。 如果保持不变,则无需更新UI!

That’s it! A brief overview of Flutter’s Stateful widget. We might work with Flutter on a daily basis here at PINCH, but even when doing so it’s necessary to take a step back sometimes and simply look at the basics again. Only then can you understand why a certain problem is arising. Stay healthy and keep coding! 🐦

而已! Flutter的有状态小部件的简要概述。 我们可能在 PINCH 上每天与Flutter进行合作 ,但是即使这样做,有时还是要退后一步,然后再次简单地看一下基础知识。 只有这样,您才能理解为什么会出现某些问题。 保持健康并保持编码! 🐦

翻译自: https://itnext.io/flutters-stateful-widget-cheat-sheet-2188f1dc3d07

flutter有状态组件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Flutter Zoomable Image 是一个用于 Flutter 应用程序的库,它提供了一个可缩放和拖动的图像小部件。使用 Flutter Zoomable Image,您可以轻松地实现图像的缩放、拖动和捏放手势操作。这对于创建具有可交互性的图像查看器和画廊等应用程序非常有用。 要使用 Flutter Zoomable Image,您需要在项目的 `pubspec.yaml` 文件中添加依赖项,并运行 `flutter packages get` 命令来获取库。 以下是一个简单的示例代码,演示了如何在 Flutter 中使用 Zoomable Image: ```dart import 'package:flutter/material.dart'; import 'package:flutter_zoomable_image/flutter_zoomable_image.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Zoomable Image Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Zoomable Image Demo'), ), body: Center( child: ZoomableImage( AssetImage('path/to/your/image.jpg'), placeholder: Center(child: CircularProgressIndicator()), backgroundColor: Colors.black, ), ), ); } } ``` 在上面的示例中,我们创建了一个简单的 Flutter 应用程序,其中包含一个使用 ZoomableImage 小部件的页面。ZoomableImage 接受一个 AssetImage 对象作为图像源,并提供了一些可选参数,例如 placeholder(用于在图像加载期间显示的小部件)和 backgroundColor(用于设置图像背景色)。 您可以根据自己的需求定制 Zoomable Image 的样式和行为。要了解更多关于 Flutter Zoomable Image 的信息和用法,请参考官方文档或库的 GitHub 页面。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值