Flutter原生界面集成插件fragment的使用

发布于 1周前 作者 bupafengyu 来自 Flutter

根据您提供的标题、内容和示例代码,看起来您提到的“fragment”并不是直接与Flutter原生界面集成插件相关的内容。实际上,“fragment”是一个用于优化Flutter应用性能的包,通过减少不必要的build()调用来提高效率。不过,我可以帮助您理解如何在Flutter中集成原生界面,并提供一个完整的示例demo。

Flutter原生界面集成插件fragment的使用

虽然这里的“fragment”不是指Android中的Fragment,但我们可以通过Flutter的平台通道(Platform Channels)来集成原生界面。下面将介绍如何使用Flutter与原生Android的Fragment进行交互。

1. 创建Flutter项目

首先,创建一个新的Flutter项目:

flutter create native_fragment_integration
cd native_fragment_integration

2. 修改Android部分以支持Fragment

android/app/src/main/kotlin/com/example/native_fragment_integration/MainActivity.kt中,我们需要修改MainActivity以支持Fragment:

package com.example.native_fragment_integration

import android.os.Bundle
import androidx.fragment.app.FragmentActivity
import io.flutter.embedding.android.FlutterFragment

class MainActivity: FragmentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Load the Flutter fragment
        val flutterFragment = FlutterFragment.withNewEngine().initialRoute("/").build<FlutterFragment>()
        supportFragmentManager.beginTransaction()
            .add(android.R.id.content, flutterFragment)
            .commit()
    }
}

3. 创建一个简单的Flutter页面

lib/main.dart中创建一个简单的Flutter页面:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Native Fragment Integration Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Native Fragment Integration'),
      ),
      body: Center(
        child: Text('This is a Flutter page.'),
      ),
    );
  }
}

4. 配置AndroidManifest.xml

确保您的android/app/src/main/AndroidManifest.xml文件中有正确的配置:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.native_fragment_integration">

    <application
        android:name="${applicationName}"
        android:label="native_fragment_integration"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

5. 测试集成效果

运行您的Flutter应用程序:

flutter run

更多关于Flutter原生界面集成插件fragment的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter原生界面集成插件fragment的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter应用中集成原生界面通常涉及平台通道(Platform Channels)的使用,以实现Flutter与原生Android或iOS代码的通信。对于在Flutter中集成Android的Fragment,我们可以通过MethodChannel或Plugin来实现。以下是一个简要的代码示例,展示如何在Flutter中调用并显示一个Android Fragment。

Flutter端代码

首先,在你的Flutter项目中创建一个新的Dart文件(例如native_view_controller.dart),用于封装与原生代码的交互逻辑。

import 'package:flutter/services.dart';

class NativeViewController {
  static const MethodChannel _channel = MethodChannel('com.example.native_view');

  Future<void> showNativeFragment() async {
    try {
      await _channel.invokeMethod('showNativeFragment');
    } on PlatformException catch (e) {
      print("Failed to invoke: '${e.message}'.");
    }
  }
}

然后,在你的Flutter组件中调用这个逻辑:

import 'package:flutter/material.dart';
import 'native_view_controller.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Native Fragment Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              NativeViewController().showNativeFragment();
            },
            child: Text('Show Native Fragment'),
          ),
        ),
      ),
    );
  }
}

Android端代码

接下来,在Android项目中创建一个新的Fragment,并配置MethodChannel以响应Flutter端的调用。

  1. 创建Fragment

在你的Android项目中创建一个新的Fragment类,例如NativeFragment.java

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class NativeFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_native, container, false);
        TextView textView = view.findViewById(R.id.text_view);
        textView.setText("This is a native Fragment!");
        return view;
    }
}

同时,创建一个布局文件fragment_native.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="16dp">

    <TextView
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Loading..."
        android:textSize="20sp" />
</LinearLayout>
  1. 配置MethodChannel

在你的MainActivity.java中配置MethodChannel以响应Flutter端的调用,并显示Fragment。

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;

public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "com.example.native_view";

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
                .setMethodCallHandler(
                        (call, result) -> {
                            if (call.method.equals("showNativeFragment")) {
                                showNativeFragment();
                                result.success(null);
                            } else {
                                result.notImplemented();
                            }
                        }
                );
    }

    private void showNativeFragment() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment nativeFragment = new NativeFragment();
        fragmentTransaction.replace(R.id.flutter_fragment_container, nativeFragment); // Ensure you have a container with this ID in your activity layout
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
}

注意:在实际应用中,你可能需要在activity_main.xml中添加一个用于容纳Fragment的容器,例如一个FrameLayout,并赋予它R.id.flutter_fragment_container的ID。然而,由于Flutter默认会占据整个屏幕,你可能需要调整FlutterEngine和Fragment的显示逻辑以适应你的具体需求。

这个示例代码展示了基本的集成逻辑,但在实际应用中,你可能需要更复杂的逻辑来处理Fragment的显示、隐藏、以及与Flutter的交互。希望这个示例能为你提供一个良好的起点。

回到顶部