Flutter 升级到1.17之后的爬坑记

网上有很多升级到1.12之后的适配问题,可以参考 Flutter升级到1.12填坑指南

  • 目前的flutter的版本是Flutter 1.17.5 • channel stable
  • 升级后activity的基类使用了io.flutter.embedding.android.FlutterFragmentActivity
  • 遇到的坑:程序启动后直接闪退,查看log提示:
No view found for id 0x245a3c5c (unknown) for fragment FlutterFragment{id=0x245a3c5c flutter_fragment}

由于不熟悉Flutter,还以为是我打开Fragment的姿势不对,于是百度了好久,找到各种打开Fragment的姿势,最终都没有解决问题。于是还是自己乖乖的断点调试,最终在FlutterFragmentActivity中的onCreate中发现

@Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    switchLaunchThemeForNormalTheme();
    super.onCreate(savedInstanceState);
    configureWindowForTransparency();
    setContentView(createFragmentContainer());
    configureStatusBarForFullscreenFlutterExperience();
    ensureFlutterFragmentCreated();
  }

private View createFragmentContainer() {
    FrameLayout container = new FrameLayout(this);
    container.setId(FRAGMENT_CONTAINER_ID);
    container.setLayoutParams(
        new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    return container;
  }

private void ensureFlutterFragmentCreated() {
    FragmentManager fragmentManager = getSupportFragmentManager();
    flutterFragment = (FlutterFragment) fragmentManager.findFragmentByTag(TAG_FLUTTER_FRAGMENT);
    if (flutterFragment == null) {
      // No FlutterFragment exists yet. This must be the initial Activity creation. We will create
      // and add a new FlutterFragment to this Activity.
      flutterFragment = createFlutterFragment();
      fragmentManager
          .beginTransaction()
          .add(FRAGMENT_CONTAINER_ID, flutterFragment, TAG_FLUTTER_FRAGMENT)
          .commit();
    }
  }

onCreate中会自己设置contentView,那我之前自己设置的contentView会把基类的覆盖,ensureFlutterFragmentCreated中添加的fragment会找不到ContainerView 。所以在自己APP的基类中添加一个ID为FRAGMENT_CONTAINER_ID的view,并设置为隐藏就OK了

 @SuppressLint("ResourceType")
    private void addNoVisibleFragment()
    {
        View view = new FrameLayout(this);
        // 这个ID是在FlutterFragmentActivity中定义的数值
        // 在FlutterFragmentActivity中会把view作为contentView
        // 但是在咱们自己的APP中会重新设置contentView
        // 所以添加一个隐藏的contentView,防止由于找不到view导致闪退
        view.setId(609893468);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        addContentView(view, params);
        view.setVisibility(View.GONE);
    }

最后还是鄙视一下Flutter,搞这么大的坑

你可能感兴趣的:(Flutter 升级到1.17之后的爬坑记)