首页 > 其他分享 >iOS项目中加入flutter

iOS项目中加入flutter

时间:2023-12-20 18:14:54浏览次数:40  
标签:const 加入 iOS flutter override import Flutter channel

新建一个iOS项目Test

在iOS同级目录下建一个flutter module

flutter create --template module my_flutter

podfile编写如下

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'Test' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!
flutter_application_path = '../my_flutter'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
install_all_flutter_pods(flutter_application_path)
  # Pods for Test

end

post_install do |installer|
  flutter_post_install(installer) if defined?(flutter_post_install)
end

 使用

  • 直接使用
  1. navigationController?.pushViewController(FlutterViewController(), animated: true)
  • 有交互的使用
  • import UIKit
    import Flutter
    // The following library connects plugins with iOS platform code to this app.
    //import FlutterPluginRegistrant
    
    @UIApplicationMain
    class AppDelegate: FlutterAppDelegate { // More on the FlutterAppDelegate.
        let engines = FlutterEngineGroup(name: "ios_fultter_double", project: nil)
    
      override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Runs the default Dart entrypoint with a default Flutter route.
    //    flutterEngine.run();
        // Connects plugins with iOS platform code to this app.
    //    GeneratedPluginRegistrant.register(with: self.flutterEngine);
        return super.application(application, didFinishLaunchingWithOptions: launchOptions);
      }
    }
    
    
    // Copyright 2021 The Flutter team. All rights reserved.
    // Use of this source code is governed by a BSD-style license that can be
    // found in the LICENSE file.
    
    import Flutter
    import FlutterPluginRegistrant
    import Foundation
    
    /// A FlutterViewController intended for the MyApp widget in the Flutter module.
    ///
    /// This view controller maintains a connection to the Flutter instance and syncs it with the
    /// datamodel.  In practice you should override the other init methods or switch to composition
    /// instead of inheritence.
    class InteractionViewController: FlutterViewController {
        private var channel: FlutterMethodChannel?
    
        init(withEntrypoint entryPoint: String?) {
            let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
            let newEngine = appDelegate.engines.makeEngine(withEntrypoint: entryPoint, libraryURI: nil)
            GeneratedPluginRegistrant.register(with: newEngine)
            super.init(engine: newEngine, nibName: nil, bundle: nil)
    
        }
    
       
    
        required init(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    
        override func viewDidLoad() {
            super.viewDidLoad()
            channel = FlutterMethodChannel(
                name: "ios_fultter_double", binaryMessenger: engine!.binaryMessenger)
            
            let navController = navigationController!
            channel!.setMethodCallHandler { (call: FlutterMethodCall, result: @escaping FlutterResult) in
                if call.method == "incrementCount" {
                    result(nil)
                } else if call.method == "next" {
                    navController.pushViewController(FlutterViewController(), animated: true)
                    result(nil)
                } else {
                    result(FlutterMethodNotImplemented)
                }
            }
        }
    }
    // Copyright 2021 The Flutter team. All rights reserved.
    // Use of this source code is governed by a BSD-style license that can be
    // found in the LICENSE file.
    
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    void main() => runApp(const MyApp(color: Colors.blue));
    
    @pragma('vm:entry-point')
    void topMain() => runApp(const MyApp(color: Colors.green));
    
    @pragma('vm:entry-point')
    void bottomMain() => runApp(const MyApp(color: Colors.purple));
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key, required this.color});
    
      final MaterialColor color;
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            colorSchemeSeed: color,
            useMaterial3: true,
            appBarTheme: AppBarTheme(
              backgroundColor: color,
              foregroundColor: Colors.white,
              elevation: 8,
            ),
          ),
          home: const MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({super.key, required this.title});
      final String title;
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      int? _counter = 0;
      late MethodChannel _channel;
    
      @override
      void initState() {
        super.initState();
        _channel = const MethodChannel('ios_fultter_double');
        _channel.setMethodCallHandler((call) async {
          if (call.method == "setCount") {
            // A notification that the host platform's data model has been updated.
            setState(() {
              _counter = call.arguments as int?;
            });
          } else {
            throw Exception('not implemented ${call.method}');
          }
        });
      }
    
      void _incrementCounter() {
        // Mutations to the data model are forwarded to the host platform.
        _channel.invokeMethod<void>("incrementCount", _counter);
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text(
                  'You have pushed the button this many times:',
                ),
                Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.headlineMedium,
                ),
                TextButton(
                  onPressed: _incrementCounter,
                  child: const Text('Add'),
                ),
                TextButton(
                  onPressed: () {
                    _channel.invokeMethod<void>("next", _counter);
                  },
                  child: const Text('Next'),
                ),
                ElevatedButton(
                  onPressed: () async {
                    // Use the url_launcher plugin to open the Flutter docs in
                    // a browser.
                    final url = Uri.parse('https://flutter.dev/docs');
                  },
                  child: const Text('Open Flutter Doc11s'),
                ),
              ],
            ),
          ),
        );
      }
    }

     

标签:const,加入,iOS,flutter,override,import,Flutter,channel
From: https://www.cnblogs.com/ZhangShengjie/p/17917158.html

相关文章

  • uniapp app安卓、ios文件选择 (上传pdf word video img )等
    1、hybrid 必须放在项目根目录下,不然会调用失效:如图 2、建立nvue 子窗体  代码:1<template>2<viewclass="nvue">3<textclass="popup-item"@click="clickfun">选择文件</text>4<textclass="ddddd......
  • iOS GCDWebServer 搭建本地服务器
    需求场景:H5页面读取系统相册,把选中的图片上传给前端H5.(H5不能直接读取沙盒的路径)方案1:读取到的二进制baseEncode字符串形式交互 弊端:安全性问题:JavaScript在浏览器中运行,可能存在潜在的安全风险,需要谨慎处理用户照片,以免导致隐私泄露或安全问题。性能问题:读取大型......
  • Flutter 使用PageView 自定义无限轮播
    import'package:flutter/material.dart';int_getRealIndex(intindex,intlength){returnindex>=length?index%length:index;}classInfinitySliderextendsStatefulWidget{finalintinitialPage;finalList<Widget>items;......
  • ● Zabbix——操作系统加入
    zabbix-get用户测试server端是否可以连通agent的key,并取回值。安装:yuminstallzabbix-get如果不知道路径,可以通过下方命令查找。find/-namezabbix_get安装完成后,可以下面命令来测试是否可以连通agent-s--host:指定客户端主机名或者IP-p--port:客户端端口,默认10050-I......
  • Flutter video_player播放视频
    1、pubspec.yaml文件引入插件dependencies:...video_player:^2.8.12、页面使用(这里我是宽度百分百,高度自适应了)lateVideoPlayerController_controller;Container(width:MediaQuery.of(context).size.width,child:AspectRatio(aspectRatio:_......
  • vue项目多axios实例动态创建
    //通用请求拦截器importaxiosfrom"axios";importQsfrom"qs";importstorefrom"@/store";importrouterfrom"@/router";import{Loading,Message}from"element-ui";//引用element-ui的加载和消息提示组件letloading......
  • 【Dotnet 工具箱】推荐一个 Flutter 和 .NET 开源的实时聊天 APP
    1.推荐一个Flutter和.NET开源的实时聊天APPHeyy-chat-appHeyy-chat-app是一个开源的聊天应用,使用Flutter、Asp.NetCoreWebApi、SignalR、WebRTC等技术构建的。Flutter作为用户客户端。Asp.NetCoreRESTful作为后端服务。Signalr和WebRTC用于实时通信。SQ......
  • KingIOServer连接S7-200 SMART PLC
    硬件:西门子200SMARTPLCSR30软件环境:1,PLC编程软件Step7Micro/WINSMART2,组态王KingIOServer具体步骤:1,打开KingIOServer工程设计器,然后新建应用/工程,输入应用名称,然后确定2,左侧项目树,设备-右键 3,左侧项目树,变量-右键,新建变量4,编译,运行 5,在弹出的窗口中,启动......
  • flutter开发总结2
    整个flutter的项目的大局观:分层架构、单一职责、模块化我们遵循这几种构建的理念,在不同的项目中可能具体的实现不同,但是大体是这样的。分层架构主要体现在如:业务逻辑层、数据层、表示层单一职责和模块化:common代表一些通用的工具类,data负责接收数据相关,page代表每个界面,login是一个......
  • Flutter 用PageView实现轮播
    import'package:flutter/material.dart';classPageSwiperextendsStatefulWidget{constPageSwiper({super.key});@overrideState<PageSwiper>createState()=>_PageSwiperState();}class_PageSwiperStateextendsState<PageSwi......