<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by ✧੯‧̀͡⬮ Doreen Chen✧ on Medium]]></title>
        <description><![CDATA[Stories by ✧੯‧̀͡⬮ Doreen Chen✧ on Medium]]></description>
        <link>https://medium.com/@doreenchen0606?source=rss-6943221dfacb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QkI8MzKGiWTdpqKgjvbD9Q.png</url>
            <title>Stories by ✧੯‧̀͡⬮ Doreen Chen✧ on Medium</title>
            <link>https://medium.com/@doreenchen0606?source=rss-6943221dfacb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:35:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@doreenchen0606/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[[Eng] tvOS Focus Engine Hands-On Guide]]></title>
            <link>https://medium.com/@doreenchen0606/eng-tvos-focus-engine-hands-on-guide-f4ec5d67976b?source=rss-6943221dfacb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4ec5d67976b</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[visionos]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[tvos]]></category>
            <category><![CDATA[apple-tv]]></category>
            <dc:creator><![CDATA[✧੯‧̀͡⬮ Doreen Chen✧]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 10:17:43 GMT</pubDate>
            <atom:updated>2025-06-03T04:27:06.358Z</atom:updated>
            <content:encoded><![CDATA[<h3>tvOS Focus Engine Hands-On Guide</h3><p>As a frontend engineer working on a streaming service, I inevitably (and unfortunately😹) spend a lot of time wrestling with the Focus Engine on tvOS. Now that visionOS is becoming more mature, it’s more important than ever to have a solid grasp on the Focus Engine, which is used in both tvOS and visionOS. So if you are interested, let’s dive in the unknown!</p><blockquote>TL;DR<br>Focus Engine automatically find the nearest focusable object. But if your layout isn’t perfectly symmetrical, you might need some tricks — like using a transparent view and a custom UIFocusGuide to tweak the default focus behavior.</blockquote><h4>Core Concept of Focus Engine</h4><p>Unlike iOS, where users can tap anywhere on the screen, Apple TV relies on a remote control to move focus step by step. That’s why fine-grained control over focus behavior is crucial for creating a smooth user experince. Let’s break it down into two key steps to master the Focus Engine</p><p><strong>Step1. Focusable Component</strong></p><p>Aside from standard UIControl components like UIButton, you can make UICollectionViewCell, UITableViewCell, and even custom UIView focusable by setting isUserInteractionEnabled=true or overriding canBecomeFocused.</p><p>There are two key functions to help you find the previous and next focusable objects and customize focus behavior:</p><ol><li>shouldUpdateFocus mainly used to restrict focus movement base on business logic</li><li>didUpdateFocus typically used to update the UI, such as highlighting the currently focused object</li></ol><pre>override func shouldUpdateFocus(in context: UIFocusUpdateContext) -&gt; Bool {<br>  // check if the item is available if needed<br>  if let nextFocusedView = context.nextFocusedView as? TabItem, nextFocusedView.isAvailable {<br>   return false<br>  }<br> <br> // check if the direction is allowed if needed<br> // https://developer.apple.com/documentation/uikit/uifocusheading<br> if context.focusHeading == .left {<br>   return false<br> }<br><br> return true<br>}<br><br>override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {<br> super.didUpdateFocus(in: context, with: coordinator)<br> coordinator.addCoordinatedAnimations {<br> // change different style for focus or unfocus object<br> self.backgroundColor = .systemGray.withAlphaComponent(self.isFocused ? 1 : 0.5)<br> }<br>}</pre><p><strong>Step2. Focus moving direction</strong></p><p>By default, the system automatically determines the nearest focusable component based on the layout.</p><figure><img alt="default focus moving direction" src="https://cdn-images-1.medium.com/max/1024/1*VUGDhxnzP98qCjHLKDx_RA.png" /><figcaption>default focus moving direction</figcaption></figure><p>However, as shown in the image above, if focus is on the first cell (Hatha), it can&#39;t move up to the tab bar because there&#39;s no focusable view above it.</p><p>To fix this, we need to add a transparent view (TabView) above the cell and use UIFocusGuide to indicate that there&#39;s still a focusable object above.</p><figure><img alt="Add a transparent view to detect the focusable region" src="https://cdn-images-1.medium.com/max/1024/1*bSUjz94mwiyhkZOUqpdrTw.png" /><figcaption>Add a transparent view to detect the focusable region</figcaption></figure><pre>/// add focusGuide into tab view<br>let tabFocusGuide = UIFocusGuide()<br>addLayoutGuide(tabFocusGuide)<br>NSLayoutConstraint.activate([<br> tabFocusGuide.topAnchor.constraint(equalTo: topAnchor),<br> tabFocusGuide.leadingAnchor.constraint(equalTo: leadingAnchor),<br> tabFocusGuide.trailingAnchor.constraint(equalTo: trailingAnchor),<br> tabFocusGuide.bottomAnchor.constraint(equalTo: bottomAnchor)<br>])</pre><figure><img alt="Successfully focus on the unsymmetrical view above" src="https://cdn-images-1.medium.com/max/1024/1*z6PP1zX0Z24otp9MQBS-qA.gif" /><figcaption>Successfully focus on the unsymmetrical view above</figcaption></figure><p>Normally, the system selected the most appropriate focusable object for us. However, we can override this behavior — such as setting focus to the currently selected tab — by overriding preferredFocusEnvironments.</p><pre>override var preferredFocusEnvironments: [any UIFocusEnvironment] {<br>  // for example we could always focus on the last tab when we move up from cell to tab view<br> if let lastItem = stackView.arrangedSubviews.last {<br> return [lastItem]<br> } else {<br> return super.preferredFocusEnvironments<br> }<br>}</pre><h4>Focus-Related Bugs and How to Fix Them</h4><p><strong>Issue 1. Layout hierarchy caused weird focus effect</strong></p><p>When a focused view scales up, it might get visually buried under other views due to the default parent-child hierarchy. Ideally, we want the focused view to appear above everything else.</p><figure><img alt="Header and cell being cropped or hide due to view hierarchy" src="https://cdn-images-1.medium.com/max/1024/1*p9y5RXnPsoIxnCBidpstJg.png" /><figcaption>Header and cell being cropped or covered due to view hierarchy</figcaption></figure><p><strong>Solution :</strong></p><ul><li>Adjust anchorPoint and zPosition to ensure the focused view stays on top.</li></ul><pre>transform = isFocused ? CGAffineTransform(scaleX: 1.15, y: 1.15) : .identity<br>// focus object should always at the top of the view hierarchy<br>layer.zPosition = isFocused ? 1 : 0<br>// scale starting point is slightly shifted to the left<br>if itemIndex == 0, isFocused {<br> anchorPoint = .init(x: 0.45, y: 0.5)<br>} else {<br> anchorPoint = .init(x: 0.5, y: 0.5)<br>}</pre><ul><li>For headers, update zPosition within the UICollectionViewDelegate methods to keep them above other elements.</li></ul><pre>func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {<br> view.layer.zPosition = -1<br>}</pre><ul><li>If you want the view to scale from its center, consider adjusting the UICollectionView size and using contentInset to create spacing instead of relying on Auto Layout.</li></ul><figure><img alt="General auto layout setting" src="https://cdn-images-1.medium.com/max/1024/1*sWeYVwUHZkSBSu6IBi1z3A.png" /><figcaption>General auto layout setting</figcaption></figure><figure><img alt="After adjusting layout to create wider CollectionView" src="https://cdn-images-1.medium.com/max/1024/1*6f-4tHwdYcS1XVO4jfLhjg.png" /><figcaption>After adjusting layout to create wider CollectionView</figcaption></figure><p><strong>Issue 2. Focus Conflicts with Other Animations</strong></p><p>When multiple animations run simultaneously, they can interfere with each other and cause unexpected behavior. For example, if we customize the tap menu action to always return focus to the first cell, it might not work as expected due to scrolling animation conflicts.</p><figure><img alt="Unexpected focus position due to focus animation conflicts" src="https://cdn-images-1.medium.com/max/1024/1*vsMOENvkyLyGYyT-5444Bw.gif" /><figcaption>Unexpected focus position due to focus animation conflicts</figcaption></figure><pre>override var preferredFocusEnvironments: [any UIFocusEnvironment] {<br>    if let firstItem = collectionView.cellForItem(at: IndexPath(item: 0, section: 0)) {<br>        return [firstItem]<br>    } else {<br>        return super.preferredFocusEnvironments<br>    }<br>}<br><br>let menuRecognizer = UITapGestureRecognizer(target: self, action: #selector(menuDidSelect))<br>menuRecognizer.allowedPressTypes = [NSNumber(value: UIPress.PressType.menu.rawValue)]<br>view.addGestureRecognizer(menuRecognizer)<br> <br>@objc<br>func menuDidSelect() {<br> // should back to the preferredFocusEnvironments position<br> setNeedsFocusUpdate()<br> updateFocusIfNeeded()<br>}</pre><p><strong>Solution:</strong></p><ul><li>Manually scroll to the target item before updating the focus.</li><li>Delay the focus update animation to ensure each transition happens in sequence, preventing unexpected glitches.</li></ul><pre>@objc<br>func menuDidSelect() {<br> // scroll by ourselves<br> collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .left, animated: true)<br> // delay focus animation<br> DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {<br> self.setNeedsFocusUpdate()<br> self.updateFocusIfNeeded()<br> }<br>}</pre><p>And that’s a wrap on all the <strong>t</strong>ips and tricks I’ve picked up from years of tvOS development! Hope this helps you out 🙌🏻</p><p>Beyond general focus management, Apple also offers <strong>Top Shelf</strong>, an interesting feature that enhances the user experience outside of your app. If you’re curious, I highly recommend checking it out!</p><p><a href="https://developer.apple.com/documentation/tvservices/tvtopshelfcontentprovider">https://developer.apple.com/documentation/tvservices/tvtopshelfcontentprovider</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4ec5d67976b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[tvOS Focus Engine 焦點管理攻略]]></title>
            <link>https://medium.com/@doreenchen0606/tvos-focus-engine-%E7%84%A6%E9%BB%9E%E7%AE%A1%E7%90%86%E6%94%BB%E7%95%A5-3cedfd7f07e3?source=rss-6943221dfacb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cedfd7f07e3</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[tvos]]></category>
            <category><![CDATA[apple-tv]]></category>
            <category><![CDATA[apple-vision-pro]]></category>
            <category><![CDATA[visionos]]></category>
            <dc:creator><![CDATA[✧੯‧̀͡⬮ Doreen Chen✧]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 06:53:49 GMT</pubDate>
            <atom:updated>2025-03-15T06:53:49.810Z</atom:updated>
            <content:encoded><![CDATA[<p>在 OTT 產業擔任前端工程師近兩年，不可避免的開發過大大小小 tvOS 功能，深受 Focus 系統少之又少的技術資源所苦，在離職前夕來濃縮一下血淚開發筆記，如果你也跟我一樣（不幸的😹）需要開發、或想要建立自己的第一個 tv App，就從這篇文章開始吧！</p><blockquote>TL;DR 🌠<br>系統會自動尋找最接近位置中，可以被 Focus 的元件。如果 UI 有不規則的結構，就會需要開發者透過在維持 UI 視覺相同下，調整 Layout (添加透明的View)，及使用 UIFocusGuide 來告知系統焦點路徑。</blockquote><p>看完喜歡的朋友的請記得訂閱按👏，讓懶人如我更有動力分享筆記下去</p><h4>Focus Engine 的核心原理</h4><p>有別於 iOS 中使用者可以透過觸控，自由選定元件操作的便利，tvOS 需要透過遙控器逐一的移動 UI 元件位置，<em>開發者也會需要透過更精細的控制，來完成流暢的使用者體驗，</em>從 Focus 管理很重要的兩步驟開始說明</p><p><strong>Step 1. 控制可以被 Focus 的元件</strong><br>除了可供使用者互動的 UIControl 元件 (UIButton等) 外，UICollectionViewCell、UITableViewCell 在宣告 isUserInteractionEnabled=true也可以被 Focus 焦點找到。如果是自定義的 UIView，則可以透過覆寫 canBecomeFocused 來控制焦點移動</p><pre>override var canBecomeFocused: Bool {<br>  true<br>}</pre><p>當元件可以被 Focus 時，有兩個關鍵方法 ，可以透過 UIFocusUpdateContext ，取得當前及下一個被 Focus 的元件，客製更細緻的操作</p><ol><li>shouldUpdateFocus 可以在 Focus 到商業邏輯上受限使用的物件時，限制其 Focus 的行為</li><li>didUpdateFocus 當物件被 Focus 後呼叫，通常用於改變 Focus 物件的樣式，以讓使用者更清楚當前位置</li></ol><pre>override func shouldUpdateFocus(in context: UIFocusUpdateContext) -&gt; Bool {<br>  // 轉型成自定義物件，並檢查物件的狀態是否為 Disable<br>  if let nextFocusedView = context.nextFocusedView as? TabItem, nextFocusedView.isDisable {<br>   return false<br>  }<br> <br> // 透過 focusHeading 取得 Focus 移動的方向，並自訂義 Focus 行為<br> // https://developer.apple.com/documentation/uikit/uifocusheading<br> if context.focusHeading == .left {<br>   return false<br> }<br><br> return true<br>}<br><br>override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {<br> super.didUpdateFocus(in: context, with: coordinator)<br> // 與系統動畫同步，不會有延遲或卡頓<br> coordinator.addCoordinatedAnimations {<br> // 被 Focus 的話變化不同的背景色<br> self.backgroundColor = .systemGray.withAlphaComponent(self.isFocused ? 1 : 0.5)<br> }<br>}</pre><p><strong>Step2. 決定 Focus 移動的位置</strong><br>定義好可以被 Focus 元件後，接下來，<em>系統會自動根據 UI 元件的排列，自動尋找最近可以被 Focus 的元件</em></p><figure><img alt="系統會自動尋找最接近可以被 Focus 的元件" src="https://cdn-images-1.medium.com/max/1024/1*VUGDhxnzP98qCjHLKDx_RA.png" /><figcaption>Focus 預設移動方向</figcaption></figure><p>這時候的排版就會發生比較常見的問題，當 Focus 停留在第一個 Cell (圖Hatha處) 時，會因為 Cell 上方沒有可以被 Focus 元件，無法順利的往上移動</p><p>此時為了讓系統知道 Cell 上方有可以 Focus 的元件，我們必須在 Tab 底層加上一層透明的 TabView (圖白色虛線處)，寬度至少要可以延伸到 Cell 往上對應的位置 (真的很 Tricky 我知道🤢)</p><figure><img alt="透過添加透明的View在背景，讓實際可以被 Focus 的區域變廣" src="https://cdn-images-1.medium.com/max/1024/1*bSUjz94mwiyhkZOUqpdrTw.png" /><figcaption>透過添加透明的 View 來延長 Tab 的所在範圍</figcaption></figure><p>接著再透過加上 UIFocusGuide，讓無法被 Focus 的 TabView，也可以順利的被系統納入 Focus 移動路徑</p><pre>/// 在 TabView 加入 UIFocusGuide <br>let tabFocusGuide = UIFocusGuide()<br>addLayoutGuide(tabFocusGuide)<br>NSLayoutConstraint.activate([<br> tabFocusGuide.topAnchor.constraint(equalTo: topAnchor),<br> tabFocusGuide.leadingAnchor.constraint(equalTo: leadingAnchor),<br> tabFocusGuide.trailingAnchor.constraint(equalTo: trailingAnchor),<br> tabFocusGuide.bottomAnchor.constraint(equalTo: bottomAnchor)<br>])</pre><figure><img alt="透過Layout調整及UIFocusGuide，順利的將 Focus 移至非對齊的物件上" src="https://cdn-images-1.medium.com/max/1024/1*z6PP1zX0Z24otp9MQBS-qA.gif" /><figcaption>順利的將 Focus 移至非對齊的物件上</figcaption></figure><p>此時系統會從 TabView 內找尋可以被 Focus 的元件，如果有需要特別指定的元件，例如選擇中的Tab，則可以透過覆寫 preferredFocusEnvironments 達成</p><pre>/// 選擇 TabView 內預設指定的 Focus 位置<br>override var preferredFocusEnvironments: [any UIFocusEnvironment] {<br>  // 方便演示差異，這邊調整為最後一個 Item<br> if let lastItem = stackView.arrangedSubviews.last {<br> return [lastItem]<br> } else {<br> return super.preferredFocusEnvironments<br> }<br>}</pre><h4><strong>常見的 Focus 衍生問題</strong></h4><p><strong>Issue 1. Focus 放大效果造成元件的遮擋</strong><br>當物件在套用放大的效果時，時常會有因為父視圖的尺寸、子視圖的層級等原因，帶來的 Focus 元件被遮擋問題</p><figure><img alt="因為 Focus 放大效果 造成的遮擋問題" src="https://cdn-images-1.medium.com/max/1024/1*fCMlZr7FKIaHMX-qP4n5gA.png" /><figcaption>因為 Focus 放大效果 造成的遮擋問題</figcaption></figure><p>此時可以透過調整 anchorPoint 及 zPosition 來針對不同問題修正</p><pre>transform = isFocused ? CGAffineTransform(scaleX: 1.15, y: 1.15) : .identity<br>// 調整被 Focus 物件的層級<br>layer.zPosition = isFocused ? 1 : 0<br>// 第一個 cell 放大時，稍微往左偏移，避免超出 collectionView 範圍被裁切<br>if itemIndex == 0, isFocused {<br> anchorPoint = .init(x: 0.45, y: 0.5)<br>} else {<br> anchorPoint = .init(x: 0.5, y: 0.5)<br>}</pre><p>第一張圖片的情境，則需要在 CollectionView 的 Delegate 方法中，調整 Header 的層級為最低</p><pre>func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {<br> view.layer.zPosition = -1<br>}</pre><p>如果希望置中放大，不想調整 anchorPoint，就會需要調整 Layout 讓 CollectionView 實際尺寸變大，再透過 contentInset 讓視覺上保持相同的間距</p><figure><img alt="原先的 Layout 邏輯，使用 Constraint 來提供間距" src="https://cdn-images-1.medium.com/max/1024/1*lTlBfz7fm_GXbVFTDSKc3w.png" /><figcaption>原先的 Layout 邏輯</figcaption></figure><figure><img alt="調整後的 Layout 邏輯，使用 ContentInset 來創造間距" src="https://cdn-images-1.medium.com/max/1024/1*BsjXWYbLEu2KpTVdAcsMAw.png" /><figcaption>調整後的 Layout 邏輯</figcaption></figure><p><strong>Issue 2. Focus 效果與其他動畫打架的狀況<br></strong>當畫面中有不同的動畫要呈現，很有可能系統底層產生衝突，導致預期外的結果，例如當添加以下點擊 menu 事件時，根據我們設定的 preferredFocusEnvironments，應該要回到第一個 Cell 上，卻因為與系統 scroll 動畫的衝突，導致並非停在我們預期的 Cell 上</p><figure><img alt="Focus 放大及CollectionView 滾動的動畫衝突，導致的非預期結果" src="https://cdn-images-1.medium.com/max/1024/1*vsMOENvkyLyGYyT-5444Bw.gif" /><figcaption>Focus 動畫衝突導致非預期結果</figcaption></figure><pre>override var preferredFocusEnvironments: [any UIFocusEnvironment] {<br>    if let firstItem = collectionView.cellForItem(at: IndexPath(item: 0, section: 0)) {<br>        return [firstItem]<br>    } else {<br>        return super.preferredFocusEnvironments<br>    }<br>}<br><br>let menuRecognizer = UITapGestureRecognizer(target: self, action: #selector(menuDidSelect))<br>menuRecognizer.allowedPressTypes = [NSNumber(value: UIPress.PressType.menu.rawValue)]<br>view.addGestureRecognizer(menuRecognizer)<br> <br>@objc<br>func menuDidSelect() {<br> // 應該要回到預設preferredFocusEnvironments的位置<br> setNeedsFocusUpdate()<br> updateFocusIfNeeded()<br>}</pre><p>此時則需要延遲 Focus 的動畫更新，確保 CollectionView 的滾動動畫完成，Focus 才會在正確的位置上</p><pre>@objc<br>func menuDidSelect() {<br> // 先滾動到指定位置<br> collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .left, animated: true)<br> // 延遲更新 focus<br> DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {<br> self.setNeedsFocusUpdate()<br> self.updateFocusIfNeeded()<br> }<br>}</pre><p>以上就是兩年開發的血淚史，根據不同的 UI 編排，可能會有不一樣的問題發生，但釐清核心概念，再到不同情境上，基本上就可解決 90% 的 Focus 問題啦 ✨</p><p>另外除了自身的 App 外，Apple 也提供了 Top Shelf 功能，讓你在外部選單就可以先預覽 App 內容，提供更優質的沈浸式體驗。因為有官方給定的固定格式，基本上照著文件提供的 API 實作都不是太困難，有興趣可以研究看看！<br><a href="https://developer.apple.com/documentation/tvservices/tvtopshelfcontentprovider">https://developer.apple.com/documentation/tvservices/tvtopshelfcontentprovider</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cedfd7f07e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter BLoC Pattern]]></title>
            <link>https://medium.com/@doreenchen0606/flutter-bloc-pattern-5611b464110f?source=rss-6943221dfacb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5611b464110f</guid>
            <category><![CDATA[flutter-future]]></category>
            <category><![CDATA[flutter-state-management]]></category>
            <category><![CDATA[flutter-stream]]></category>
            <category><![CDATA[bloc-pattern]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[✧੯‧̀͡⬮ Doreen Chen✧]]></dc:creator>
            <pubDate>Fri, 04 Aug 2023 04:26:08 GMT</pubDate>
            <atom:updated>2023-08-04T04:26:08.292Z</atom:updated>
            <content:encoded><![CDATA[<p>繼上一篇Flutter的狀態管理，要接著介紹因應狀態管理需求而生的設計模式<strong>BLoC(Business Logic Components) Pattern</strong>。BLoC會在架構內扮演MVVM內ViewModel的角色，用以將UI與Data業務邏輯的程式碼解耦，底層則透過Stream的技術來實現非同步的事件接收及狀態傳遞。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*V_TQw6xQSCdLj7elNoGVwg.png" /><figcaption>Source: <a href="https://bloclibrary.dev/#/architecture">https://bloclibrary.dev/#/architecture</a></figcaption></figure><p>以下先來簡單介紹Stream，對於BLoC實作會比較有概念</p><h4>Stream</h4><p>Stream提供非同步的資料佇列，透過FIFO的方式處理資料，例如：在Flutter中的 files.openRead() 方法就是透過Stream的方式，依序讀取檔案內的Data。</p><blockquote><a href="https://dart.dev/tutorials/language/streams">Stream</a>和Future都是Dart中提供非同步資料的方式，差異在於Stream可以提供多次的資料，Future僅能提供一次性的資料。</blockquote><p>Stream依據訂閱者的數量，分為Single及Broadcast兩種類型。 <strong>Single Subscription Stream</strong>，會持有事件直到有訂閱者訂閱該Stream，且一次僅能被一個訂閱者訂閱，建立方式可以透過 轉換Stream、StreamController、 async*等方式建立。當希望可以讓多個訂閱者訂閱Stream的話，則必須使用 <strong>Broadcast Streams</strong>。</p><p>以下舉例async*的建立方式：</p><pre>Future&lt;int&gt; sumStream(Stream&lt;int&gt; stream) async {<br>  var sum = 2;<br>  // await for為異步的迴圈，可以待接收到Stream最終值時再執行<br>  await for (final value in stream) {<br>    print(&quot;數量：$value&quot;);<br>    sum += value;<br>  }<br>  return sum;<br>}<br><br>// 透過async*建立Stream<br>Stream&lt;int&gt; countStream(int to) async* {<br>  for (int i = 1; i &lt;= to; i++) {<br>    // 持續發送事件<br>    yield i;<br>  }<br>}<br><br>void main() async {<br>  var stream = countStream(5);<br>  var sum = await sumStream(stream);<br>  print(sum);<br>}<br><br>/*<br>數量：1<br>數量：2<br>數量：3<br>數量：4<br>數量：5<br>57<br>*/</pre><p>以上Log的結果可以得知Stream在建立時，就會開始接收事件，套用在Bloc上，可以不斷地接收來自使用者諸如加入購物車、移除購物車等事件，而不需要撰寫多餘的程式碼。接下來就回過頭看BLoC的實作方式，這邊我是採用 👍🏻最高(? 的套件 <a href="https://pub.dev/packages/flutter_bloc">flutter_bloc</a>：</p><h3>BLoC實作</h3><p>在開始前會需要先思考怎麼拆解APP的架構，以電商APP舉例，會需要「產品總覽」、「個別產品資訊」、「購物車」、「結帳」等四個BLoC。下圖示意首頁的產品總覽BLoC，其中包括事件及狀態的類型：</p><p>事件對應的會是使用者觸發的行為，故除了初載入的「初始狀態」的事件外，如果APP有提供加入最愛功能，則可以新增「加入最愛」的事件等；狀態的部分則會根據Repository取得的資料，分別遞送「載入中」、「已載入(成功)」、「載入失敗」的狀態，頁面再依據接收到的不同狀態，去顯示對應的UI。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uhNTZy4DjuzhJ_Qbv9rjyA.png" /></figure><p>以程式來逐步實現：</p><h4>1. 建立BLoC</h4><p>所有的BLoC皆需繼承Bloc這個Class，並定義Event及State的類別，在接收到event時，做相對應的資料處理及透過 emit 發送State。</p><pre>class ProductBloc extends Bloc&lt;ProductEvent, ProductState&gt; {<br>  // 建立repository接口<br>  final Repository _repository = Repository();<br><br>  // 將Event轉換為State<br>  ProductBloc(): super(ProductLoadingState()) {<br>    on&lt;ProductInitialEvent&gt;((event, emit) async { // 接收到evnet後執行後面的Block<br>      // 先發送Loading的狀態<br>      emit(ProductLoadingState());<br>      try {<br>        // 發送載入完畢的狀態及Data<br>        final products = await _repository.getProducts(EndPoint.all);<br>        emit(ProductLoadedState(products));<br>      } catch (e) {<br>        // 發送錯誤狀態<br>        emit(ProductErrorState(e.toString()));<br>      }<br>    });<br>  }<br>}</pre><p>定義Event 及 State的類型，兩者皆需要遵從<a href="https://pub.dev/packages/equatable">Equtable</a>，並複寫其中的props屬性，以在比對物件的時候，可以根據其中的props來比對身份。</p><pre>@immutable<br>abstract class ProductEvent extends Equatable {<br>  const ProductEvent();<br>}<br><br>class ProductInitialEvent extends ProductEvent {<br>  @override<br>  List&lt;Object&gt; get props =&gt; [];<br>}</pre><pre>@immutable<br>abstract class ProductState extends Equatable {}<br><br>class ProductLoadingState extends ProductState {<br>  @override<br>  List&lt;Object&gt; get props =&gt; [];<br>}<br><br>class ProductLoadedState extends ProductState {<br>  ProductLoadedState(this.products);<br>  final List&lt;Product&gt; products;<br><br>  // 載入成功時會回傳的產品清單<br>  @override<br>  List&lt;Object&gt; get props =&gt; [products];<br>}<br><br>class ProductErrorState extends ProductState {<br>  ProductErrorState(this.error);<br>  final String error;<br>  // 載入失敗時會回傳的錯誤訊息<br>  @override<br>  List&lt;Object&gt; get props =&gt; [error];<br>}</pre><h4>2. BLoC 使用</h4><p>flutter_bloc的套件並不會直接取用Bloc，會透過BlocProvider創建Bloc，並把變動傳遞給使用到的子Widget，故需要先在MyApp的層級建立Provider，再透過 add 呼叫初始化event。</p><pre>BlocProvider(create: (_) =&gt; ProductBloc()..add(ProductInitialEvent())),</pre><p>在需要使用狀態的Widget，透過BlocBuilder的方式接收狀態，當狀態改變時，BlocBuilder會自動重新渲染畫面，產生對應狀態的UI。</p><pre>BlocBuilder&lt;ProductBloc, ProductState&gt;(<br>    builder: (context, state) {<br>        if (state is ProductLoadingState) {<br>            return const Center(<br>                child: CircularProgressIndicator.adaptive(<br>                    valueColor: AlwaysStoppedAnimation(Colors.grey)));<br>        } else if (state is ProductErrorState) {<br>            return const Center(child: Text(&#39;Error&#39;));<br>        } else if (state is ProductLoadedState) {<br>            // 透過state.products讀取成功後接收到的資料<br>            handleCallbackData(state.products);<br>            return body();<br>        }<br>        return Container();<br>    }<br>)</pre><p>✨最後補充，BLoC pattern只是一種設計模式，可以選擇自己實作，也可以使用不同的第三方套件，即使是同一個套件使用的方式也不盡相同，所以寫法沒有標準答案，可以根據自己的使用情境及需求來選擇最適合的喔 ！</p><p><strong><em>參考資料</em></strong></p><ul><li>Stream <a href="https://ithelp.ithome.com.tw/articles/10247333">https://ithelp.ithome.com.tw/articles/10247333</a></li></ul><p><strong><em>延伸閱讀</em></strong></p><ul><li>手把手Bloc教學 <a href="https://www.youtube.com/watch?v=n11VJTdtc2c&amp;ab_channel=ABNationProgrammers">https://www.youtube.com/watch?v=n11VJTdtc2c&amp;ab_channel=ABNationProgrammers</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5611b464110f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter State Management 狀態管理]]></title>
            <link>https://medium.com/@doreenchen0606/flutter-state-management-%E7%8B%80%E6%85%8B%E7%AE%A1%E7%90%86-b68a1435a3fa?source=rss-6943221dfacb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b68a1435a3fa</guid>
            <dc:creator><![CDATA[✧੯‧̀͡⬮ Doreen Chen✧]]></dc:creator>
            <pubDate>Sun, 16 Apr 2023 14:19:28 GMT</pubDate>
            <atom:updated>2023-04-16T14:19:28.860Z</atom:updated>
            <content:encoded><![CDATA[<p>Flutter開發系列第一篇，先來談談貫穿整個框架不可或缺的 “狀態管理”，因為過往iOS開發經驗著重在指令式語法 (Imperative) 的操作，所以一開始學習最大的檻，其實是熟悉宣告式語法 (Declarative)，如何在不同物件中溝通的方式，也就是今天要討論的議題 “狀態管理”。</p><p>如果你跟我一樣是指令式語法起家的XD，在開始之前需要建立以下幾個Mindset：</p><ul><li>過往指令式語法可以在接收到事件時，輕易地獲取指定物件，並更改其狀態；但在宣告式語法中，因為無法任意取得指定物件，故需仰賴於<strong><em>事前將狀態與指定物件(UI)綁定，以在狀態變動時自動更新UI</em></strong>。</li><li>在Flutter中，所有的元件都是Widget，必須實作build方法建構UI。<strong><em>當狀態變動時，會銷毀該Widget，並呼叫build方法重新建構UI</em></strong>，故若有不想跟著被銷毀的資料，就必須透過狀態管理來保存。</li><li>建構UI時會透過Widget Tree的方式，來辨識每個對象的身份，當狀態需要被多個Widget共享時，<strong><em>必須考量狀態需要擺放在Widget Tree的階層位置</em></strong>，以避免因為狀態改變連動銷毀Widget時，造成不必要的性能消耗。</li></ul><p>Flutter中的狀態依據需要保存的期間，可以分為短暫狀態(Ephemeral State)及應用狀態(App State)，以下將針對各自情境適用的狀態管理方式介紹：</p><h3>短暫狀態 (Ephemeral State)</h3><p>當狀態不需要被其他Widget共享時即為短暫狀態，當頁面關閉時，狀態也會被清除，通常使用在用戶操作介面上的狀態紀錄。如果已經開過Flutter範例專案的人，其實也已經接觸到最常見的短暫狀態管理方法，那就是透過<a href="https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html">StatefulWidget</a> 達成。</p><blockquote>Flutter除了StatefulWidget外，另也有提供無狀態使用的 <a href="https://api.flutter.dev/flutter/widgets/StatelessWidget-class.html">StatelessWidget</a> 喔！</blockquote><h4>StatefulWidget</h4><p>StatefulWidget讓Widget可以保存其內屬性的狀態，並在狀態改變時更新UI，以下先來逐一了解StatefulWidget的生命週期：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*afJ95LPnPEi3ssyI.png" /><figcaption>Source: <a href="https://mobikul.com/lifecycle-of-a-flutter-app/">https://mobikul.com/lifecycle-of-a-flutter-app/</a></figcaption></figure><ul><li><strong>createState()</strong></li></ul><p>當建構StatefulWidget時，會透過其提供的方法 createState() 產生可變的狀態實例，並將Widget與其State進行關聯，避免Widget被重建時State遺失。此時 mounted 會被設定為 true。</p><blockquote>mounted 用來判斷當前 State 是否被加載到Widget Tree中。當有非同步操作時，可以透過判斷 mounted，確認 State 是否存在，再進行對應操作。</blockquote><pre>class MyHomePage extends StatefulWidget {<br>  @override<br>  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState(); <br>  // 回傳含有MyHomePage狀態的類別<br>}</pre><ul><li><strong>initState()</strong></li></ul><p>建構StatefulWidget後第一個執行的方法，且僅會執行一次，會在Widget繪製前執行，可以在這個階段執行資料初始化、訂閱Stream等設定。</p><pre>@override<br>void initState(){<br>  super.initState();<br>}</pre><ul><li><strong>didChangeDependencies()</strong></li></ul><p>調用 initState()後立即調用 didChangeDependencies()，後續當StatefulWidget更新就不會再被調用，除非 StatefulWidget 依賴的InheritedWidget 發生變化後，才會被再次調用。</p><pre>@override<br>void didChangeDependencies() { <br>}</pre><ul><li><strong>build()</strong></li></ul><p>用來渲染UI的方法，除了初始化外，當Widget狀態有更新時就會被調用以更新UI。</p><pre>@override<br>Widget build(BuildContext context, MyButtonState state) {<br>      return Container(color: const Color(0xFF2DBD3A));     <br>}</pre><ul><li><strong>didUpdateWidget(Widget oldWidget)</strong></li></ul><p>當父Widget的狀態改變時，就會調用子Widget的 didUpdateWidget()，因為被調用的時機不可控，且執行完後會接著調用 build()更新畫面，故通常不會主動複寫didUpdateWidget()。</p><pre>@protected<br>void didUpdateWidget(Home oldWidget) {<br>  super.didUpdateWidget(oldWidget);<br>}</pre><ul><li><strong>setState()</strong></li></ul><p>需要開發者主動調用，在State Object內的屬性變動的時候，可以呼叫 setState()來更新屬性，Flutter就會緊接呼叫 build()，以重新繪製UI。</p><pre>setState(() {<br> // TODO: update property inside<br>});</pre><ul><li><strong>deactivate()</strong></li></ul><p>當State Object即將被銷毀而移除Widget Tree，或是當State要重新被插入Widget Tree（如換頁）時調用。</p><pre>@override<br>void deactivate(){<br>  super.deactivate();<br>}</pre><ul><li><strong>dispose()</strong></li></ul><p>當State Object被永久移除時調用，通常會在這裡取消訂閱監聽或是動畫等設定。此時 mounted 會被設為 false。</p><pre>@override<br>void dispose(){<br>   super.dispose();<br>}</pre><p>以下簡單示意常用情境，當使用者點擊左邊側邊欄按鈕時，切換右邊頁面：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gppUUVcSwTLDK7_mRyTwmg.png" /></figure><pre>class MyHomePage extends StatefulWidget {<br>  @override<br>  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState(); // 建立State實例<br>}<br><br>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br><br>  var selectedIndex = 0;<br><br>  @override<br>  Widget build(BuildContext context) {<br><br>    Widget page; // 事前定義數據(selectedIndex)對應的頁面<br>    switch (selectedIndex) {<br>      case 0:<br>        page = GeneratorPage();<br>        break;<br>      case 1:<br>        page = FavoritesPage();<br>        break;<br>      default:<br>        throw UnimplementedError(&#39;no widget for $selectedIndex&#39;);<br>    }<br><br>    return LayoutBuilder(<br>      builder: (context, constraints) {<br>        return Scaffold(<br>          body: Row(<br>            children: [<br>              SafeArea( // 建立左邊側邊欄<br>                child: NavigationRail(<br>                  extended: constraints.maxWidth &gt;= 600,<br>                  destinations: [<br>                    NavigationRailDestination(<br>                      icon: Icon(Icons.home),<br>                      label: Text(&#39;Home&#39;),<br>                    ),<br>                    NavigationRailDestination(<br>                      icon: Icon(Icons.favorite),<br>                      label: Text(&#39;Favorites&#39;),<br>                    ),<br>                  ],<br>                  selectedIndex: selectedIndex,<br>                  onDestinationSelected: (value) {<br>                    setState(() { // 透過setState()方法，告知框架數據變動重建Widget<br>                      selectedIndex = value;<br>                    });<br>                  },<br>                ),<br>              ),<br>              Expanded( // 建立右邊頁面<br>                child: Container(<br>                  color: Theme.of(context).colorScheme.primaryContainer,<br>                  child: page,<br>                ),<br>              ),<br>            ],<br>          ),<br>        );<br>      }<br>    );<br>  }<br>}</pre><h3>應用狀態 (App State)</h3><p>需要被多個Widget共享的狀態，當頁面關閉時仍不影響既有狀態。可以透過InheritedWidget 綁定Widget與其子組件的依賴關係，結合 StatefulWidget、ChangeNotifier 或者 Steam 使用，當其狀態發生變化時，可以自動更新其所有依賴的子組件。</p><blockquote><a href="https://api.flutter.dev/flutter/widgets/InheritedWidget-class.html">InheritedWidget</a> 提供在 Widget Tree 中從上到下傳遞數據的方法，Flutter中常用的 Theme, Style, MediaQuery等就是 InheritedWidget，所以在程式里的各種地方都可以訪問到它們。</blockquote><p>但因為操作繁雜，故另有框架封裝 InheritedWidget 及 ChangeNotifier 等功能，推出簡易的使用的 <a href="https://pub.dev/packages/provider">Provider</a> 框架（也是官方教材的使用框架喔！），以下就針對功能成熟的 Provider 框架進行介紹：</p><h4>Provider</h4><p>Provider 以觀察者模式的方式實現應用狀態管理，以下逐步介紹實現方式：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*weX4RWQDIUUDv9zOE1KOnw.png" /><figcaption>Source: <a href="https://www.dltlabs.com/blog/create-a-login-screen-with-providerpattern-523088">https://www.dltlabs.com/blog/create-a-login-screen-with-providerpattern-523088</a></figcaption></figure><ol><li><strong>建立Model</strong></li></ol><p>將Model繼承 <strong>ChangeNotifier</strong>，並在資料更新時，透過 notifyListener() 通知訂閱的Widget進行對應的畫面更新。</p><pre>class CartModel extends ChangeNotifier {<br>  final List&lt;Item&gt; _items = [];<br><br>  void add(Item item) {<br>    _items.add(item);<br>    notifyListeners(); // 通知所有訂閱者<br>  }<br><br>  void removeAll() {<br>    _items.clear();<br>    notifyListeners(); // 通知所有訂閱者<br>  }<br>}</pre><p><strong>2. 提供數據</strong></p><p>透過 provider package 的 <strong>ChangeNotifierProvider</strong>，向其子節點暴露一個 ChangeNotifier<strong> </strong>的實例，當數據改變時，會重建Consumer並更新UI。<strong>ChangeNotifierProvider</strong>不會隨Widget的銷毀重複創建實例，且會在不需使用時自動調用其 dispose()。</p><pre>void main() {<br>  runApp(<br>    ChangeNotifierProvider(<br>      create: (context) =&gt; CartModel(), // 創建ChangeNotifier實例<br>      child: const MyApp(), // MyApp下的子節點皆可獲取CartModel實例<br>    ),<br>  );<br>}</pre><p>當有多個數據需要提供時，可以透過 <strong>MultiProvider </strong>實現。</p><pre>void main() {<br>  runApp(<br>    MultiProvider(<br>      providers: [ // 返回多個ChangeNotifier實例<br>        ChangeNotifierProvider(create: (context) =&gt; CartModel()),<br>        Provider(create: (context) =&gt; SomeOtherClass()),<br>      ],<br>      child: const MyApp(),<br>    ),<br>  );<br>}</pre><p>另外還有以下幾種Provider類型，有興趣可以參考官方文件說明及範例</p><ul><li>FutureProvider：具初始值，接收一個Future，並在進入complete階段時更新依賴組建。</li><li>StreamProvider：監聽流，暴露當前最新的數據，並多次觸發重建UI，適用於每n秒就需要重新撈取最新數據上。</li><li>ProxyProvider：能夠將多個Provider的值聚合為一個新對象，將結果傳遞給Provider。</li><li>ChangeNotifierProxyProvider：同上，差異在於會將聚合的結果傳遞給NotifierProvider，故當值改變時，可以同步更新UI。</li><li>ListenableProvider：ChangeNotifierProvider的父類別，當需自行實現Listenable或使用動畫時使用。</li></ul><p><strong>3. 使用數據</strong></p><p>一個方式是透過 <strong>Consumer </strong>調用數據，當 <strong>ChangeNotifierProvider </strong>呼叫notifyListener() 時，所有關聯 Widget 的 builder函數都會一併被調用。</p><p>⚠️ 須將 Consumer 盡量放置在層級較低的地方，如下例的 Text()，避免被多次不必要的銷毀重建。</p><pre>return Consumer&lt;CartModel&gt;( // 角括號內加上需要拿的Model型別<br>// 第二個參數為實際拿到的model<br>// 第三個參數為當模型改變時，可以避免該Widget被重建<br>  builder: (context, cart, child) =&gt; Stack(<br>    children: [<br>      if (child != null) child,<br>      Text(&#39;Total price: ${cart.totalPrice}&#39;),<br>    ],<br>  ),<br>  // Build the expensive widget here.<br>  child: const SomeExpensiveWidget(),<br>);</pre><p>另一個方式是可以透過 <strong>Provider.of()</strong> 來調用數據。將 listen參數改為false，可以將監聽狀態關閉，不用每次觸發notifyListeners()時都跟著一起被重構。</p><pre>Provider.of&lt;CartModel&gt;(context, listen: false) // 將listen改為false</pre><h4>參考資料</h4><ul><li>StatefulWidget 生命週期 <a href="https://mobikul.com/lifecycle-of-a-flutter-app/">https://mobikul.com/lifecycle-of-a-flutter-app/</a></li></ul><h4>延伸閱讀</h4><ul><li>透過InheritedWidget實作應用狀態管理 <a href="https://medium.com/flutter/managing-flutter-application-state-with-inheritedwidgets-1140452befe1">https://medium.com/flutter/managing-flutter-application-state-with-inheritedwidgets-1140452befe1</a></li><li>不同的Provider範例 <a href="https://juejin.cn/post/7067356022272163847">https://juejin.cn/post/7067356022272163847</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b68a1435a3fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>