Unresolved reference: R when trying to create home screen widget in Flutter app

234 Views Asked by At

I have a flutter app and want to add a home screen widget to the app. I use home_widget package and follow the tutorial for android app. home_widget package

My flutter code have two flavor settings for two apps with different application ID. I want to add home screen widget only for one flavor.

When I compile, it always gets an error. Unresolved reference: R at these two lines:

val layoutId = R.layout.widget_layout

setTextViewText(R.id.appwidget_text, title ?: "No text set")

This is my full file android/app/src/main/kotlin/my/domain/app_name_flavor1/MyAppWidgetProvider.kt

package my.domain.app_name_flavor1

import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.SharedPreferences
import android.widget.RemoteViews
import my.domain.app_name_flavor1.HomeWidgetProvider


class MyAppWidgetProvider : HomeWidgetProvider() {

    override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, 
                            appWidgetIds: IntArray, widgetData: SharedPreferences) {
        // TODO fix Unresolved reference: R error
        for (appWidgetId in appWidgetIds) {
            val widgetData = HomeWidgetPlugin.getData(context)
            val layoutId = R.layout.widget_layout
            val views = RemoteViews(context.packageName, layoutId).apply {

                val title = widgetData.getString("appwidget_text", null)
                // val title = "default"
                setTextViewText(R.id.appwidget_text, title ?: "No text set")
            }

            appWidgetManager.updateAppWidget(appWidgetId, views)


        }
    }
}

I try removing all code about R in this kotlin. The app has a static home screen widget as set in android/app/src/flavor1/res/layout/widget_layout.xml

I try upgrade flutter, cleaning and rebuilding with flutter clean and ./gradlew clean. None of those solves the issue.

What can I do to fix this error?

1

There are 1 best solutions below

1
On

You shouldn't remove the R references in the code, but instead, import this:

import my.domain.app_name_flavor1.R