Friday, September 30, 2022
HomeiOS Developmentios - Easy methods to add a FlutterViewController to a UIViewController

ios – Easy methods to add a FlutterViewController to a UIViewController


I discovered an answer which provides the flutter view to the view controller.

// create an extension for all UIViewControllers
extension UIViewController {
     /**
         Add a flutter sub view to the UIViewController
         units constraints to edge to edge, overlaying all elements on the display 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 }

        // permits 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 structure
        flutterView.layoutIfNeeded()
    }
}

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

override func viewDidLoad() {
    tremendous.viewDidLoad()
    
    // get the flutter engine for the view
    let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
    
    // add flutter view
    addFlutterView(with: flutterEngine)

    // Do any extra setup after loading the view.
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular