More
How to Create Home Screen Widgets in Flutter with HomeWidget and Back4App
31 min
introduction home screen widgets allow users to access real time information from your app directly on their device's home screen without opening the app with flutter, creating these widgets requires some platform specific code however, the home widget https //pub dev/packages/home widget package bridges this gap by enabling data exchange between your flutter app and the home screen widgets using dart code in this tutorial, you will learn how to create a home screen widget in flutter using the home widget package and integrate it with back4app—a backend as a service powered by parse server by the end of this tutorial, you will have a flutter app that displays data from back4app in a home screen widget prerequisites to complete this tutorial, you will need flutter sdk installed on your machine you can follow the official flutter installation guide https //flutter dev/docs/get started/install for your operating system basic knowledge of flutter and dart if you're new to flutter, consider reviewing the flutter documentation https //flutter dev/docs to familiarize yourself with the basics an ide or text editor such as visual studio code or android studio a back4app account sign up for a free account at back4app https //www back4app com/ parse server sdk for flutter added to your project you can learn how to set it up by following the back4app flutter sdk guide https //www back4app com/docs/flutter/parse flutter sdk platform specific setup for android and ios home screen widgets step 1 – setting up the flutter project 1 1 create a new flutter project open your terminal and run flutter create home widget app navigate to the project directory cd home widget app 1 2 add dependencies open pubspec yaml and add the following dependencies dependencies flutter sdk flutter home widget ^0 2 4 parse server sdk flutter ^4 0 1 run flutter pub get to install the packages step 2 – setting up back4app 2 1 create a new back4app application log in to your back4app dashboard https //dashboard back4app com/ click on "create new app" enter a name for your application, e g , "homewidgetapp" , and click "create" 2 2 set up the data model in your application dashboard, navigate to the "database" section click on "create a class" in the modal select "custom" enter "message" as the class name click "create class" 2 3 add columns to the class in the "message" class, click on "+" to add a new column add the following columns title type string content type string add some sample data to the "message" class for example 2 4 obtain application credentials navigate to app settings > security & keys note down your application id and client key step 3 – initializing parse in your flutter app open lib/main dart and modify it as follows import 'package\ flutter/material dart'; import 'package\ parse server sdk flutter/parse server sdk dart'; import 'package\ home widget/home widget dart'; import 'dart\ async'; import 'home page dart'; // you'll create this file next void main() async { widgetsflutterbinding ensureinitialized(); const keyapplicationid = 'your application id'; const keyclientkey = 'your client key'; const keyparseserverurl = 'https //parseapi back4app com'; await parse() initialize( keyapplicationid, keyparseserverurl, clientkey keyclientkey, debug true, ); runapp(myapp()); } replace 'your application id' and 'your client key' with your actual back4app credentials step 4 – fetching data from back4app create a new file lib/home page dart import 'package\ flutter/material dart'; import 'package\ parse server sdk flutter/parse server sdk dart'; import 'package\ home widget/home widget dart'; import 'dart\ async'; class homepage extends statefulwidget { @override homepagestate createstate() => homepagestate(); } class message { final string title; final string content; message(this title, this content); } class homepagestate extends state\<homepage> { message? message; @override void initstate() { super initstate(); fetchmessage(); } future\<void> fetchmessage() async { final querybuilder\<parseobject> query = querybuilder\<parseobject>(parseobject('message')); final parseresponse apiresponse = await query query(); if (apiresponse success && apiresponse results != null) { final data = apiresponse results! first; final title = data get\<string>('title') ?? ''; final content = data get\<string>('content') ?? ''; setstate(() { message = message(title, content); }); updatehomewidget(title, content); } else { print('error fetching data ${apiresponse error? message}'); } } future\<void> updatehomewidget(string title, string content) async { await homewidget savewidgetdata\<string>('title', title); await homewidget savewidgetdata\<string>('content', content); await homewidget updatewidget( name 'homewidgetprovider', // name of your homewidgetprovider iosname 'homewidget'); // used in ios } @override widget build(buildcontext context) { return scaffold( appbar appbar( title text('home widget app'), ), body center( child message == null ? circularprogressindicator() column( mainaxisalignment mainaxisalignment center, children \[ text( message! title, style textstyle(fontsize 24, fontweight fontweight bold), ), sizedbox(height 10), text( message! content, style textstyle(fontsize 18), ), sizedbox(height 20), elevatedbutton( onpressed fetchmessage, child text('refresh message'), ), ], ), ), ); } } explanation message class a simple model class to hold the message data fetchmessage() fetches data from the message class in back4app and updates the message variable updatehomewidget() saves the fetched data to the home screen widget using homewidget savewidgetdata and triggers an update using homewidget updatewidget build() displays the message data and a button to refresh the message step 5 – setting up the home screen widget 5 1 android setup 5 1 1 create the widget layout create a new xml layout file in android/app/src/main/res/layout/ named home widget xml \<! android/app/src/main/res/layout/home widget xml > \<?xml version="1 0" encoding="utf 8"?> \<framelayout xmlns\ android="http //schemas android com/apk/res/android" android\ layout width="match parent" android\ layout height="match parent"> \<textview android\ id="@+id/widget title" android\ layout width="wrap content" android\ layout height="wrap content" android\ text="title" android\ textsize="18sp" android\ layout gravity="center horizontal|top" android\ paddingtop="16dp"/> \<textview android\ id="@+id/widget content" android\ layout width="wrap content" android\ layout height="wrap content" android\ text="content" android\ textsize="14sp" android\ layout gravity="center" android\ paddingtop="8dp"/> \</framelayout> 5 1 2 create the widget provider create a new java class in android/app/src/main/java/your/package/name/ named homewidgetprovider java // android/app/src/main/java/your/package/name/homewidgetprovider java package your package name; import android appwidget appwidgetmanager; import android appwidget appwidgetprovider; import android content context; public class homewidgetprovider extends appwidgetprovider { @override public void onupdate(context context, appwidgetmanager appwidgetmanager, int\[] appwidgetids) { // the homewidget package handles the update } } replace your package name with your actual package name 5 1 3 update android manifest add the widget provider to your androidmanifest xml \<! add inside the \<application> tag > \<receiver android\ name=" homewidgetprovider"> \<intent filter> \<action android\ name="android appwidget action appwidget update"/> \</intent filter> \<meta data android\ name="android appwidget provider" android\ resource="@xml/home widget info"/> \</receiver> 5 1 4 create widget info xml create a new xml file in android/app/src/main/res/xml/ named home widget info xml \<! android/app/src/main/res/xml/home widget info xml > \<?xml version="1 0" encoding="utf 8"?> \<appwidget provider xmlns\ android="http //schemas android com/apk/res/android" android\ initiallayout="@layout/home widget" android\ minwidth="180dp" android\ minheight="110dp" android\ updateperiodmillis="0" android\ resizemode="horizontal|vertical" android\ widgetcategory="home screen"> \</appwidget provider> 5 2 ios setup 5 2 1 create a widget extension open your flutter project in xcode by opening ios/runner xcworkspace click file > new > target choose widget extension and click next enter homewidget as the product name and ensure include configuration intent is unchecked click finish and activate the scheme 5 2 2 update the widget code in the homewidget extension, open homewidget swift and modify it import widgetkit import swiftui struct provider timelineprovider { func placeholder(in context context) > simpleentry { simpleentry(date date(), title "title", content "content") } func getsnapshot(in context context, completion @escaping (simpleentry) > ()) { let entry = simpleentry(date date(), title "title", content "content") completion(entry) } func gettimeline(in context context, completion @escaping (timeline\<entry>) > ()) { var entries \[simpleentry] = \[] let shareddefaults = userdefaults(suitename "your group id") let title = shareddefaults? string(forkey "title") ?? "title" let content = shareddefaults? string(forkey "content") ?? "content" let entrydate = date() let entry = simpleentry(date entrydate, title title, content content) entries append(entry) let timeline = timeline(entries entries, policy never) completion(timeline) } } struct simpleentry timelineentry { let date date let title string let content string } struct homewidgetentryview view { var entry provider entry var body some view { vstack { text(entry title) font( headline) text(entry content) font( body) } } } @main struct homewidget widget { let kind string = "homewidget" var body some widgetconfiguration { staticconfiguration(kind kind, provider provider()) { entry in homewidgetentryview(entry entry) } configurationdisplayname("home widget") description("this is a home screen widget ") } } replace your group id with your app group identifier (e g , group com example homewidgetapp ) 5 2 3 set up app groups in xcode, select your project and go to signing & capabilities add "app groups" to both your main app target and the widget extension create a new app group (e g , group com example homewidgetapp ) ensure both targets have the same app group enabled 5 3 update flutter code for platform specific configurations in your updatehomewidget() method in home page dart , update the widget names await homewidget updatewidget( name 'homewidgetprovider', // for android, the class name of your appwidgetprovider iosname 'homewidget', // for ios, the name of your widget extension ); step 6 – running the app and testing the widget 6 1 run the app in your terminal, run flutter run 6 2 add the widget to your home screen android long press on the home screen and select "widgets" find your app in the widget list drag and drop the widget onto your home screen ios enter jiggle mode by long pressing on the home screen tap the "+" button in the top left corner search for your widget by name add the widget to your home screen 6 3 test data updates tap the "refresh message" button in your app to fetch new data from back4app the widget on your home screen should update with the new data conclusion in this tutorial, you learned how to create a home screen widget in flutter using the home widget package and integrated it with back4app to display dynamic data this allows you to provide users with up to date information right on their home screens, enhancing engagement and user experience next steps dynamic data implement real time data updates using back4app's live queries interactivity add click actions to your widget to open specific pages in your app customization style your widget to match your app's theme and design additional resources back4app documentation https //www back4app com/docs home widget package on pub dev https //pub dev/packages/home widget parse sdk for flutter guide https //docs parseplatform org/flutter/guide/ flutter official documentation https //flutter dev/docs happy coding!