Flutter总结集合

2020-07-08  本文已影响0人  OliverChu

1.开发Android Plugin获取Activity对象的方法

public class OliverkitPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {

  private lateinit var channel : MethodChannel
  private lateinit var activity:Activity
  private lateinit var application: Context

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.flutterEngine.getDartExecutor(), "oliverkit")
    channel.setMethodCallHandler(this)
    this.application = flutterPluginBinding.applicationContext
  }

  companion object {
    @JvmStatic
    fun registerWith(registrar: Registrar) {
      val channel = MethodChannel(registrar.messenger(), "oliverkit")
      channel.setMethodCallHandler(OliverkitPlugin())
    }
  }

  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
    if (call.method == "getPlatformVersion") {
      result.success("Android ${android.os.Build.VERSION.RELEASE}")
    } else if (call.method == "launch") {
      activity.startActivity(Intent(activity,MainActivity::class.java))
      result.success("Success")
    } else {
      result.notImplemented()
    }
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }

  override fun onDetachedFromActivity() {

  }

  override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    onAttachedToActivity(binding)
  }

  override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    this.activity = binding.activity
  }

  override fun onDetachedFromActivityForConfigChanges() {
  }

}

2. 如果需要在initState中获取数据,那么更新的时候请使用下列方式进行更新State

WidgetsBinding.instance.addPostFrameCallback((_) {
  if(mounted){
    setState(() {});
  }      
});

3. 不要直接把属性给Text() 赋值,请用下列方式

Text(
  ‘$_text’
)

4. 如果你的设备屏幕有适配需求,请使用GridView而不要使用ListView

为什么这么做呢,因为使用GridView可以动态去设置crossAxisCount,一行展示不同的数量,避免内容Item过大

5. 万物都是Widget,对于能复用的Widget,尽情去封装吧

上一篇下一篇

猜你喜欢

热点阅读