【问题标题】:How to get static context in FlutterPlugin如何在 FlutterPlugin 中获取静态上下文
【发布时间】:2021-02-23 09:46:22
【问题描述】:

我想在 FlutterPlugin 中设置静态 get 和 set context 方法,我应该如何用 kotlin 的方式实现呢?

class FlutterPushPlugin : FlutterPlugin {
    private var context: Context? = null

    fun getContext(): Context? {
        return this.context
    }

    fun setContext(context: Context?) {
        this.context = context
    }
}

// In another class
FlutterPushPlugin.getContext  // return the context property in FlutterPushPlugin

【问题讨论】:

    标签: android flutter kotlin


    【解决方案1】:

    您可以使用伴随对象或对象本身来完成这项工作,但强烈建议将上下文放在静态对象中,因为这可能会导致内存泄漏。但如果你这样做,你必须非常小心如何使用它们。现在回答你的问题:

    object StaticContext {
        var context: Context? = null
    }
    

    或者

    class FlutterPushPlugin : FlutterPlugin {
    
        companion object {
            var context: Context? = null
        }
    }
    

    不需要getter 和setter,因为Kotlin 在使用var 时会生成它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-22
      • 2021-02-06
      • 1970-01-01
      • 2019-05-28
      • 1970-01-01
      • 2012-04-29
      相关资源
      最近更新 更多