iosswiftflutteruiviewcontrollerflutter-add-to-app

How to add a FlutterViewController to a UIViewController


All the documentation that I can find for Flutter's Add-to-App demonstrates how to push/segue/present a newly created FlutterViewController. I need to add a flutter view to a tab within a tabbar. I tried changing my class's super class from UIViewController to FlutterViewController which worked, but is not using the flutter engine that is created within the app delegate. This solution resulted in showing in the launch screen before the flutter view, which isn't desired.

How do I add a flutter view to a UIViewController? Or how do I assign an engine to a FlutterViewController from within the class?


Solution

  • I found a solution which adds the flutter view to the view controller.

    // create an extension for all UIViewControllers
    extension UIViewController {
         /**
             Add a flutter sub view to the UIViewController
             sets constraints to edge to edge, covering all components on the screen
         */
        func addFlutterView(with engine: FlutterEngine) {
            // create the flutter view controller
            let flutterViewController = FlutterViewController(engine: engine, nibName: nil, bundle: nil)
            
            addChild(flutterViewController)
            
            guard let flutterView = flutterViewController.view else { return }
    
            // allows constraint manipulation
            flutterView.translatesAutoresizingMaskIntoConstraints = false
    
            view.addSubview(flutterView)
            
            // set the constraints (edge-to-edge) to the flutter view
            let constraints = [
                flutterView.topAnchor.constraint(equalTo: view.topAnchor),
                flutterView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
                flutterView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
                flutterView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
            ]
    
            // apply (activate) the constraints
            NSLayoutConstraint.activate(constraints)
    
            flutterViewController.didMove(toParent: self)
            
            // updates the view with configured layout
            flutterView.layoutIfNeeded()
        }
    }
    

    with any UIViewController, you can add a flutter subview now.

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // get the flutter engine for the view
        let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
        
        // add flutter view
        addFlutterView(with: flutterEngine)
    
        // Do any additional setup after loading the view.
    }