How to get setInitialRoute to start my Flutter iOS app on different views?

2.5k Views Asked by At

In flutter I have this:

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      routes: <String, WidgetBuilder> {
        '/Cards': (BuildContext context) => new PageSelectorDemo(),
      },
      onGenerateRoute: (RouteSettings settings) => new MaterialPageRoute(
        builder: (BuildContext ctx) => new PageSelectorDemo(),
      ),
      theme: new ThemeData(
        primarySwatch: Colors.deepPurple,
      ),
      home: new MyHomePage(title: 'Flutter View'),
    );
  }
}

In my iOS code I have this:

func getFlutterController() -> UIViewController?
{
    self.flutterController = FlutterViewController(project: nil, nibName: nil, bundle: nil)

    if let controller = self.flutterController
    {
        controller.setInitialRoute("/Cards") // setting the route
        self.messageChannel = FlutterBasicMessageChannel.init(name: "channel", binaryMessenger: controller, codec: FlutterStandardMessageCodec.sharedInstance())
        if let channel = self.messageChannel
        {
            channel.setMessageHandler() { (message:Any?, reply:FlutterReply) in
                ViewController.counter += 1
                self.labelMessage.text = "message recieved: \(ViewController.counter)"
            }
        }
    }
    return self.flutterController
}

Why doesn't this work? The flutter code just loads the initial view and not my view from the "/Cards" route.

2

There are 2 best solutions below

0
On

I found problem is self.flutterEngine?.run(withEntrypoint: nil) in document Add Flutter to existing apps. If you do like that, FlutterEngine will run before you create FlutterViewController so you cannot setInitialRoute. To solve, you must remove that line in AppDelegate, init FlutterViewController without FlutterEngine let flutterViewController = FlutterViewController(nibName: nil, bundle: nil), and setInitialRoute, final call flutterEngine?.run(withEntrypoint: nil).

0
On

I too have been having issues with setting the initial route from iOS and it looks like it may be a bug in flutter: https://github.com/flutter/flutter/issues/27216