Adding a Home Screen widget to your Flutter App

1. Introduction

What are widgets?

For Flutter developers, the term widget usually refers to UI components created using the Flutter framework. In the context of this codelab, a Home Screen widget refers to a compact view of an app that presents information from the app without opening it. On Android, widgets live on the home screen. On iOS, they can be added to the home screen, lock screen, or the Today View.

iOS Home Screen displaying a weather widget and calendar widget alongside app icons

Android Home Screen displaying a clock and weather widget above app icons

How complex can a widget be?

Most Home Screen widgets focus on glanceable content. They might contain concise text, graphics, or, on Android, basic controls. Both Android and iOS limit what UI components and features you can use inside a Home Screen widget.

Example Home Screen widgets displaying fitness activity rings and battery levels

Example Home Screen widgets displaying a music player and task checklist

Create the UI for widgets

Because of these platform UI constraints, you can't directly draw the UI of a Home Screen widget using the Flutter framework. Instead, you add widgets created with platform frameworks such as SwiftUI (WidgetKit) on iOS or AppWidget XML layouts on Android to your Flutter app. This codelab demonstrates how to share data, font assets, and rendered Flutter widgets between your main app and your Home Screen widgets so you don't have to rewrite complex UI in platform code.

What you'll build

In this codelab, you'll collaborate with Google Antigravity to build a Flutter news reader app and connect it to Home Screen widgets on both Android and iOS using the home_widget package. Your Home Screen widgets will:

  • Show article headline and description data from your Flutter app.
  • Display text using custom font assets (Chewy) shared from the Flutter app.
  • Display an image of a rendered Flutter CustomPaint chart widget.

Home Screen widget displaying a news article headline, summary, and line chart on a mobile home screen

The Flutter news app includes two screens (routes):

  • The first screen displays a list of news articles with headlines and descriptions.
  • The second screen displays the full article along with a line chart created using CustomPaint and a button to update the Home Screen widget.

Flutter news app Top Stories screen listing four articles with titles and descriptions

Flutter news app article detail screen showing body text, a line chart, and the Update Homescreen button

Your learning journey

This codelab guides you through building the app and its Home Screen widgets step by step:

  1. Set up your Flutter environment - Configure the Flutter SDK, Google Antigravity, and Xcode or Android Studio for your target platform.
  2. Create the starter news app - Prompt Antigravity to scaffold the homescreen_widgets Flutter app with home_widget, the Chewy font, and the article list and detail screens.
  3. Add a basic Home Screen widget - Create the NewsWidgets iOS Widget Extension in Xcode and the NewsWidget Android App Widget in Android Studio.
  4. Send data from your Flutter app to your Home Screen widget - Configure iOS App Groups, prompt Antigravity to wire up HomeWidget.saveWidgetData and HomeWidget.updateWidget, and read the shared data in Swift and Kotlin.
  5. Use custom fonts in your iOS Home Screen widget - Load and register the bundled Chewy-Regular.ttf font asset from the Flutter app bundle inside the iOS widget extension.
  6. Render Flutter widgets as an image - Prompt Antigravity to capture the LineChart widget as a PNG using HomeWidget.renderFlutterWidget and display the rendered chart inside both the iOS and Android Home Screen widgets.

What you'll learn

  • How to collaborate with Google Antigravity to iteratively build and connect a Flutter app with iOS and Android Home Screen widgets.
  • How to create Home Screen widgets on iOS and Android.
  • How to use the home_widget package to share data between your Home Screen widget and your Flutter app.
  • How to reuse Flutter fonts and rendered Flutter widgets in your Home Screen widget to reduce duplicate UI code.
  • How to trigger Home Screen widget updates from your Flutter app.

Prerequisites

  • Familiarity with Flutter widgets and Dart syntax.

2. Set up your Flutter environment

Editor

This codelab uses Google Antigravity as your AI-first development environment, paired with Xcode (for iOS widget targets) or Android Studio (for Android widget targets). In each step, you prompt Antigravity to generate or update your Dart and platform widget files, review the key concepts in the generated code, and optionally explore creative variations.

Choose a development target

To create the iOS Home Screen widget

  • You can run this codelab on a physical iOS device or the iOS Simulator.
  • You must use a macOS system with the Xcode IDE installed to add the Widget Extension target, configure App Groups, and build the iOS version of your app.

To create the Android Home Screen widget

  • You can run this codelab on a physical Android device or the Android Emulator.
  • You must configure your development system with Android Studio to build the Android version of your app and use the App Widget wizard.

Install Flutter

The most up-to-date instructions on installing the Flutter SDK are always on docs.flutter.dev.

For this codelab, install the following software:

  1. Flutter SDK
  2. Google Antigravity with the official Dart and Flutter plugin enabled (available in the Plugin Marketplace under the Build with Google section).
  3. Compiler and platform tools for your chosen mobile target (Xcode to target iOS, or Android Studio to target Android).

3. Create the starter news app

In this step, you prompt Antigravity to scaffold the homescreen_widgets Flutter project, install the home_widget and material_ui packages, bundle the Chewy custom font, and create the two-screen news reader application.

Prompt Antigravity to create the project

  1. Launch Google Antigravity and open an empty directory where you'd like to build your project (choose a path that doesn't require elevated privileges or contain spaces, such as a folder in your home directory or C:\src\).
  2. In the Antigravity agent chat panel, send the following prompt to create the Flutter project, add the dependencies and font asset, and generate the starter news app:
Create a new empty Flutter project named `homescreen_widgets` targeting Android and iOS (`flutter create --empty homescreen_widgets --platforms=android,ios --org=com.mydomain`). Add the `cupertino_icons`, `shared_preferences`, `home_widget`, and `material_ui` packages. Download `Chewy-Regular.ttf` from `https://raw.githubusercontent.com/flutter/codelabs/main/homescreen_codelab/step_03/fonts/Chewy-Regular.ttf` into `fonts/Chewy-Regular.ttf` and register the `Chewy` font family in `pubspec.yaml`. Using `package:material_ui/material_ui.dart`, create the starter news reader app:
- `lib/news_data.dart` defining a `NewsArticle` class (`title`, `description`, `articleText = loremIpsum`, and optional `image`) and a `getNewsStories()` function returning sample Flutter news articles.
- `lib/article_screen.dart` defining an `ArticleScreen` stateful widget that displays the article's `description`, `articleText`, a centered 200x200 `LineChart` widget drawn with a `CustomPainter` (`LineChartPainter`), and a `FloatingActionButton.extended` labeled `'Update Homescreen'` that shows a `SnackBar` (`'Updating home screen widget...'`).
- `lib/home_screen.dart` defining a `MyHomePage` stateful widget with an `AppBar` titled `'Top Stories'` and a `ListView.separated` of `getNewsStories()` where tapping a `ListTile` navigates to `ArticleScreen(article: article)`.
- `lib/main.dart` configuring `MaterialApp` with a `Colors.deepPurple` seed color scheme, `titleMedium: TextStyle(fontFamily: 'Chewy', fontSize: 20)`, and `home: const MyHomePage()`.

Understanding the generated code

Modeling news articles (lib/news_data.dart)

lib/news_data.dart defines the NewsArticle data class and provides mock stories through getNewsStories():

class NewsArticle {
  final String title;
  final String description;
  final String? articleText;
  final String? image;

  NewsArticle({
    required this.title,
    required this.description,
    this.articleText = loremIpsum,
    this.image,
  });
}

Painting the article chart (lib/article_screen.dart)

lib/article_screen.dart renders the selected NewsArticle along with a 200x200 LineChart widget backed by LineChartPainter, a CustomPainter that draws axes, a threshold line, and connected data points onto a Canvas:

class LineChart extends StatelessWidget {
  const LineChart({super.key});

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: LineChartPainter(),
      child: const SizedBox(height: 200, width: 200),
    );
  }
}

Run and test the app

Run the starter app on your iOS Simulator, Android Emulator, or connected mobile device to verify that the Top Stories list and ArticleScreen render as expected:

flutter run

4. Add a basic Home Screen widget

Before connecting your Dart code, add a basic Home Screen widget target using the platform tooling for iOS, Android, or both.

Create a basic iOS Home Screen widget

Adding a Widget Extension to a Flutter iOS app follows the same workflow as adding one to a SwiftUI or UIKit app:

  1. Open ios/Runner.xcworkspace in Xcode by running open ios/Runner.xcworkspace from your homescreen_widgets project directory.
  2. Select File → New → Target from the Xcode menu to add a new target to the project.
  3. Select Widget Extension from the template list and click Next.
  4. Enter NewsWidgets into the Product Name box. Clear both the Include Live Activity and Include Configuration Intent (or Include Configuration App Intent) checkboxes, and click Finish.

Inspect the generated code

When you add the target, Xcode generates boilerplate WidgetKit code in ios/NewsWidgets/NewsWidgets.swift and ios/NewsWidgets/NewsWidgetsBundle.swift. For more details on WidgetKit extensions, see Apple's app extension documentation.

Debug and test your sample widget

  1. Update your Flutter app's iOS configuration whenever you add new packages or targets before building from Xcode. In your homescreen_widgets directory, run:
flutter build ios --config-only
  1. In Xcode's scheme selector next to the Run button, click Runner, select the NewsWidgetsExtension (or NewsWidgets) target you just created, and click Run.

Xcode scheme selector menu showing the Runner and NewsWidgetsExtension targets

  1. The simulator or device displays a placeholder Home Screen widget showing the current time. If it doesn't appear automatically, touch and hold an empty area on the iOS Home Screen, then tap the + button in the top-left corner:

iOS Home Screen in jiggle mode with the add widget plus button in the top-left corner

  1. Search for Homescreen Widgets in the widget gallery and add the widget to your Home Screen:

iOS widget gallery search results showing the Homescreen Widgets app

Create a basic Android Home Screen widget

  1. Open the homescreen_widgets/android directory in Android Studio.
  2. Once Gradle sync finishes, locate the app module in the Project pane on the left. Right-click app and select New → Widget → App Widget.

Android Studio context menu showing New, Widget, and App Widget

  1. In the New Android Component dialog, configure your Home Screen widget with the following values and click Finish:
  • Class Name: NewsWidget
  • Minimum Width (cells): 3
  • Minimum Height (cells): 3

Inspect the generated files

Android Studio creates and updates the following files in your Android project (you can also ask Antigravity to scaffold these files directly if you aren't using the Android Studio wizard):

Action

Target File

Change

Update

AndroidManifest.xml

Registers a for .NewsWidget handling APPWIDGET_UPDATE.

Create

res/layout/news_widget.xml

Defines the Home Screen widget XML layout.

Create

res/xml/news_widget_info.xml

Configures widget dimensions, update period, and preview layout.

Create

java/com/mydomain/homescreen_widgets/NewsWidget.kt

Defines the NewsWidget : AppWidgetProvider() class.

Debug and test your sample widget

Build and run your Flutter application on your Android device or emulator. Once installed, touch and hold the app icon on the launcher screen and select Widgets from the menu to place the widget on your home screen.

Android launcher icon context menu showing the Widgets option

5. Send data from your Flutter app to your Home Screen widget

Now that you have a basic Home Screen widget on your device, you'll update it to display the headline and description of a news article from your Flutter app.

iOS Home Screen widget displaying the Flutter DAU headline and summary text

Sharing data between your Flutter app and your Home Screen widget involves three parts:

  1. Configuring an iOS App Group in Xcode so the Runner app and widget extension share a local storage container.
  2. Updating the Dart code to write headline data and trigger widget refreshes using package:home_widget/home_widget.dart.
  3. Updating the iOS (NewsWidgets.swift) and Android (news_widget.xml and NewsWidget.kt) widget implementations to read and render the saved strings.

Configure iOS App Groups

On iOS, a parent app and its Widget Extension run in separate sandboxes. To share local UserDefaults data and files between them, both targets must belong to the same App Group. For background on App Groups, see Apple's Configuring App Groups documentation.

  1. In Xcode, open the Runner target settings and select the Signing & Capabilities tab. Verify that your Team and Bundle Identifier are set.
  2. Click + Capability, select App Groups, and click the + button under App Groups to add a new group identifier (for example, group.com.mydomain.homescreenWidgets).
  3. Select the NewsWidgetsExtension target in Xcode, open Signing & Capabilities, add the App Groups capability, and select the exact same App Group identifier.

Xcode Signing and Capabilities tab showing the App Groups capability enabled

How home_widget shares data

Both iOS and Android provide a local key-value store: UserDefaults on iOS and SharedPreferences on Android. The home_widget package wraps these platform APIs so your Flutter code can save key-value pairs and notify the active Home Screen widgets to reload their views.

Architecture flow showing the Flutter app writing key-value data to UserDefaults and SharedPreferences and the Home Screen widget reading it

Prompt Antigravity to send and display article data

In the Antigravity agent chat panel, send the following prompt to wire up home_widget in Dart and update both the iOS and Android Home Screen widgets to display headline_title and headline_description:

Connect the Flutter app to the iOS and Android Home Screen widgets using `package:home_widget/home_widget.dart`:
1. In `lib/home_screen.dart`, define constants `appGroupId = '<YOUR APP GROUP>'`, `iOSWidgetName = 'NewsWidgets'`, and `androidWidgetName = 'NewsWidget'`. Add a top-level `updateHeadline(NewsArticle newHeadline)` function that saves `'headline_title'` (`newHeadline.title`) and `'headline_description'` (`newHeadline.description`) using `HomeWidget.saveWidgetData<String>` and triggers `HomeWidget.updateWidget(iOSName: iOSWidgetName, androidName: androidWidgetName)`. In `_MyHomePageState.initState()`, call `HomeWidget.setAppGroupId(appGroupId)` and `updateHeadline(getNewsStories()[0])`.
2. In `lib/article_screen.dart`, import `home_screen.dart` and call `updateHeadline(widget.article)` inside the `FloatingActionButton.extended` `onPressed` callback.
3. Update `ios/NewsWidgets/NewsWidgets.swift` (creating it if needed) with a `NewsArticleEntry: TimelineEntry` struct (`date`, `title`, `description`), a `NewsWidgetsEntryView` displaying `Text(entry.title)` and `Text(entry.description)` in a `VStack`, and a `Provider: TimelineProvider` that reads `"headline_title"` and `"headline_description"` from `UserDefaults(suiteName: "<YOUR APP GROUP>")` in `getSnapshot`.
4. Update `android/app/src/main/res/layout/news_widget.xml` and `android/app/src/main/java/com/mydomain/homescreen_widgets/NewsWidget.kt` (creating them and registering `.NewsWidget` in `AndroidManifest.xml` if needed) so `onUpdate` reads `"headline_title"` and `"headline_description"` using `HomeWidgetPlugin.getData(context)` and updates `R.id.headline_title` and `R.id.headline_description` with `setTextViewText`.

After Antigravity applies these changes, replace in both lib/home_screen.dart and ios/NewsWidgets/NewsWidgets.swift with the App Group identifier you configured in Xcode.

Understanding the generated code

Saving widget data from Flutter (lib/home_screen.dart and lib/article_screen.dart)

In lib/home_screen.dart, updateHeadline writes headline_title and headline_description to the shared platform store and calls HomeWidget.updateWidget to request an immediate widget reload on iOS and Android:

const String appGroupId = '<YOUR APP GROUP>';
const String iOSWidgetName = 'NewsWidgets';
const String androidWidgetName = 'NewsWidget';

void updateHeadline(NewsArticle newHeadline) {
  HomeWidget.saveWidgetData<String>('headline_title', newHeadline.title);
  HomeWidget.saveWidgetData<String>(
    'headline_description',
    newHeadline.description,
  );
  HomeWidget.updateWidget(
    iOSName: iOSWidgetName,
    androidName: androidWidgetName,
  );
}

In _MyHomePageState.initState(), the app registers the iOS App Group ID with HomeWidget.setAppGroupId(appGroupId) and seeds the widget with the first story. In lib/article_screen.dart, pressing the Update Homescreen FloatingActionButton calls updateHeadline(widget.article) to push the currently viewed story to the Home Screen widget.

Reading data in the iOS WidgetKit TimelineProvider (ios/NewsWidgets/NewsWidgets.swift)

On iOS, NewsArticleEntry conforms to TimelineEntry and holds the date, title, and description passed to NewsWidgetsEntryView:

struct NewsArticleEntry: TimelineEntry {
    let date: Date
    let title: String
    let description: String
}

struct NewsWidgetsEntryView : View {
    var entry: Provider.Entry

    var body: some View {
      VStack {
        Text(entry.title)
        Text(entry.description)
      }
    }
}

Provider implements TimelineProvider using three methods:

  1. placeholder(in:): Returns a placeholder NewsArticleEntry when the user first previews the widget in the iOS widget gallery.

iOS widget preview displaying Placeholder Title and Placeholder description

  1. getSnapshot(in:completion:): Reads "headline_title" and "headline_description" from UserDefaults(suiteName: "") and constructs a NewsArticleEntry for the current state:
func getSnapshot(in context: Context, completion: @escaping (NewsArticleEntry) -> ()) {
  let entry: NewsArticleEntry
  if context.isPreview {
    entry = placeholder(in: context)
  } else {
    let userDefaults = UserDefaults(suiteName: "<YOUR APP GROUP>")
    let title = userDefaults?.string(forKey: "headline_title") ?? "No Title Set"
    let description = userDefaults?.string(forKey: "headline_description") ?? "No Description Set"
    entry = NewsArticleEntry(date: Date(), title: title, description: description)
  }
  completion(entry)
}
  1. getTimeline(in:completion:): Wraps the snapshot entry in a Timeline with the .atEnd reload policy so WidgetKit refreshes the widget when requested.

Reading data in the Android AppWidgetProvider (NewsWidget.kt and news_widget.xml)

On Android, android/app/src/main/res/layout/news_widget.xml defines two TextView elements (@+id/headline_title and @+id/headline_description) inside a RelativeLayout.

In android/app/src/main/java/com/mydomain/homescreen_widgets/NewsWidget.kt, onUpdate retrieves the shared preferences using HomeWidgetPlugin.getData(context) and populates both TextViews on the widget's RemoteViews:

class NewsWidget : AppWidgetProvider() {
    override fun onUpdate(
            context: Context,
            appWidgetManager: AppWidgetManager,
            appWidgetIds: IntArray,
    ) {
        for (appWidgetId in appWidgetIds) {
            val widgetData = HomeWidgetPlugin.getData(context)
            val views = RemoteViews(context.packageName, R.layout.news_widget).apply {

                val title = widgetData.getString("headline_title", null)
                setTextViewText(R.id.headline_title, title ?: "No title set")

                val description = widgetData.getString("headline_description", null)
                setTextViewText(R.id.headline_description, description ?: "No description set")
            }

            appWidgetManager.updateAppWidget(appWidgetId, views)
        }
    }
}

Run and test the app

Rebuild and run your app (and the NewsWidgetsExtension target in Xcode if testing on iOS). Open any article in the app and tap Update Homescreen. Return to your device's home screen to verify that the widget displays the selected article's headline and description:

Android Home Screen widget displaying the Remembering Flutter Forward headline and summary

6. Use custom fonts in your iOS Home Screen widget

Your Flutter app uses the custom Chewy font family (fonts/Chewy-Regular.ttf) for article subheadings. On iOS, Flutter packages its assets inside Frameworks/App.framework/flutter_assets within the main application bundle. Your iOS Widget Extension can access that shared bundle directory and register the font with Core Text so your SwiftUI widget matches your Flutter app's typography.

Prompt Antigravity to register and apply the custom font on iOS

Send the following prompt in the Antigravity agent chat panel:

Update `NewsWidgetsEntryView` in `ios/NewsWidgets/NewsWidgets.swift` to use the Flutter app's bundled `Chewy` font for the headline title:
1. Add a computed `bundle: URL` property on `NewsWidgetsEntryView` that checks if `Bundle.main.bundleURL.pathExtension == "appex"` and, if so, navigates up two directory levels and appends `"Frameworks/App.framework/flutter_assets"`.
2. Add an `init(entry: Provider.Entry)` initializer that assigns `self.entry = entry` and registers `bundle.appending(path: "/fonts/Chewy-Regular.ttf")` using `CTFontManagerRegisterFontsForURL(..., CTFontManagerScope.process, nil)`.
3. Apply `.font(Font.custom("Chewy", size: 13))` to `Text(entry.title)` in `body`.

Understanding the generated code

Locating the Flutter asset bundle from an .appex extension

Because the widget runs inside an .appex bundle (MY_APP.app/PlugIns/MY_APP_EXTENSION.appex), the computed bundle property peels off two directory levels to reach the parent app bundle and appends Frameworks/App.framework/flutter_assets:

var bundle: URL {
    let bundle = Bundle.main
    if bundle.bundleURL.pathExtension == "appex" {
        // Peel off two directory levels - MY_APP.app/PlugIns/MY_APP_EXTENSION.appex
        var url = bundle.bundleURL.deletingLastPathComponent().deletingLastPathComponent()
        url.append(component: "Frameworks/App.framework/flutter_assets")
        return url
    }
    return bundle.bundleURL
}

Registering and applying the font

In NewsWidgetsEntryView.init(entry:), CTFontManagerRegisterFontsForURL registers /fonts/Chewy-Regular.ttf for the current process so SwiftUI's Font.custom("Chewy", size: 13) can render the headline:

init(entry: Provider.Entry) {
    self.entry = entry
    CTFontManagerRegisterFontsForURL(
        bundle.appending(path: "/fonts/Chewy-Regular.ttf") as CFURL,
        CTFontManagerScope.process,
        nil
    )
}

var body: some View {
    VStack {
        Text(entry.title).font(Font.custom("Chewy", size: 13))
        Text(entry.description)
    }
}

Run and test the app

Re-run the widget target from Xcode. The iOS Home Screen widget now renders the article headline in the Chewy font:

iOS Home Screen widget rendering the article headline in the custom Chewy font

7. Render Flutter widgets as an image

Recreating a custom Flutter visualization—such as LineChart drawn with CustomPainter—twice in SwiftUI and Android XML would require maintaining duplicate drawing code across three languages. Instead, HomeWidget.renderFlutterWidget lets you rasterize any Flutter widget into a PNG file in the shared container and pass its path to your iOS and Android Home Screen widgets.

Prompt Antigravity to render the Flutter chart and display it in the widgets

Send the following prompt in the Antigravity agent chat panel:

Render the `LineChart` Flutter widget to an image and display it in both the iOS and Android Home Screen widgets:
1. In `lib/article_screen.dart`, import `package:home_widget/home_widget.dart` and add `final _globalKey = GlobalKey();` and `String? imagePath;` to `_ArticleScreenState`. Attach `key: _globalKey` to the `Center` widget wrapping `const LineChart()`. Make the `FloatingActionButton.extended` `onPressed` callback `async`: when `_globalKey.currentContext != null`, call `await HomeWidget.renderFlutterWidget(const LineChart(), key: 'filename', logicalSize: _globalKey.currentContext!.size!, pixelRatio: MediaQuery.of(_globalKey.currentContext!).devicePixelRatio)`, store the returned path in `imagePath` with `setState()`, and then call `updateHeadline(widget.article)`.
2. In `ios/NewsWidgets/NewsWidgets.swift`, add `let filename: String` and `let displaySize: CGSize` to `NewsArticleEntry`, pass placeholder values in `placeholder(in:)`, read `userDefaults?.string(forKey: "filename") ?? "No screenshot available"` and `context.displaySize` in `getSnapshot`, and add a `ChartImage` computed view on `NewsWidgetsEntryView` that loads `UIImage(contentsOfFile: entry.filename)` into a resizable `Image` framed at `entry.displaySize.height * 0.5` and renders `ChartImage` below the description in `VStack`.
3. In `android/app/src/main/res/layout/news_widget.xml`, add an `<ImageView android:id="@+id/widget_image" ... />` below `@+id/headline_description`. In `android/app/src/main/java/com/mydomain/homescreen_widgets/NewsWidget.kt`, read `widgetData.getString("filename", null)` in `onUpdate`, check if `File(imageName).exists()`, decode the file with `BitmapFactory.decodeFile(imageFile.absolutePath)`, and call `setImageViewBitmap(R.id.widget_image, myBitmap)`.

Keep your real App Group ID in ios/NewsWidgets/NewsWidgets.swift when updating getSnapshot.

Understanding the generated code

Capturing the Flutter widget as a PNG (lib/article_screen.dart)

In _ArticleScreenState, _globalKey is attached to the Center widget wrapping const LineChart() so the app can read its rendered size and devicePixelRatio. When the user taps Update Homescreen, HomeWidget.renderFlutterWidget renders const LineChart() to a PNG file in the shared container and stores its path in local storage under the 'filename' key:

floatingActionButton: FloatingActionButton.extended(
  onPressed: () async {
    if (_globalKey.currentContext != null) {
      var path = await HomeWidget.renderFlutterWidget(
        const LineChart(),
        key: 'filename',
        logicalSize: _globalKey.currentContext!.size!,
        pixelRatio:
            MediaQuery.of(_globalKey.currentContext!).devicePixelRatio,
      );
      setState(() {
        imagePath = path;
      });
    }
    updateHeadline(widget.article);
  },
  label: const Text('Update Homescreen'),
),

Displaying the rendered image on iOS (ios/NewsWidgets/NewsWidgets.swift)

In NewsWidgets.swift, getSnapshot reads the "filename" path from UserDefaults and passes it along with context.displaySize in NewsArticleEntry. NewsWidgetsEntryView defines a ChartImage computed property that loads the PNG file with UIImage(contentsOfFile: entry.filename) and scales it to 50% of the widget's height:

var ChartImage: some View {
    if let uiImage = UIImage(contentsOfFile: entry.filename) {
        let image = Image(uiImage: uiImage)
            .resizable()
            .frame(
                width: entry.displaySize.height * 0.5,
                height: entry.displaySize.height * 0.5,
                alignment: .center
            )
        return AnyView(image)
    }
    print("The image file could not be loaded")
    return AnyView(EmptyView())
}

Displaying the rendered image on Android (news_widget.xml and NewsWidget.kt)

In android/app/src/main/res/layout/news_widget.xml, an sits beneath @+id/headline_description. In NewsWidget.kt, onUpdate reads the "filename" path from widgetData, decodes the PNG file into a Bitmap with BitmapFactory.decodeFile, and updates the ImageView using setImageViewBitmap:

val imageName = widgetData.getString("filename", null)
val imageFile = File(imageName)
val imageExists = imageFile.exists()
if (imageExists) {
    val myBitmap: Bitmap = BitmapFactory.decodeFile(imageFile.absolutePath)
    setImageViewBitmap(R.id.widget_image, myBitmap)
} else {
    println("image not found!, looked @: ${imageName}")
}

Run and test the app

Re-run both your Flutter app and your platform widget target. Open an article page in the app and tap Update Homescreen. The Home Screen widget updates with the article headline, summary, and the rendered LineChart image:

iOS Simulator showing the article detail screen alongside the Home Screen widget displaying the headline, description, and line chart

8. Congratulations!

Congratulations! You've built and connected Home Screen widgets for both iOS and Android to your Flutter app using Google Antigravity and home_widget.

What you've built

  • A two-screen Flutter news app using material_ui, custom Chewy typography, and a CustomPainter line chart.
  • Native iOS (WidgetKit / SwiftUI) and Android (AppWidgetProvider / RemoteViews) Home Screen widgets.
  • Key-value data synchronization between Dart, UserDefaults (using iOS App Groups), and SharedPreferences.
  • Cross-bundle custom font registration in an iOS Widget Extension.
  • Offscreen Flutter widget rasterization (HomeWidget.renderFlutterWidget) displayed inside both iOS and Android Home Screen widgets.

Next steps

Linking to content in your Flutter app

You might want to route users to a specific screen in your Flutter app when they tap your Home Screen widget—for example, opening the full article for the displayed headline. You can use the widgetClicked stream provided by home_widget to detect widget launches and pass deep-link URIs into your app. To learn more, see the deep linking documentation on docs.flutter.dev.

Updating your widget in the background

In this codelab, you triggered Home Screen widget updates from an in-app button. In production, you can schedule periodic background updates using the workmanager plugin together with home_widget. To learn more, see the Background Update documentation for home_widget.

On iOS, you can also schedule periodic timeline refreshes or background network requests directly through WidgetKit's TimelineProvider. See Apple's Keeping a widget up to date documentation.

Resources