Fetch arguments in Flutter module

余生颓废 提交于 2021-02-04 21:39:42

问题


I have a native Android app. I imported a Flutter module. Now, I can successfully navigate to the selected route from my Android app. I know passing data between native and flutter side is by method channels. But I did not understand how to implement it when starting the Activity.

Here is my GitHub repo.

startActivity(
         new FlutterActivity.NewEngineIntentBuilder(MyFlutterActivity.class)
                   .initialRoute("/secondScreen")
                   .build(getApplicationContext())
                   .putExtra("title", "Hello")); // Here, title is passed!

How can I handle this title on my initState of secondScreen?

class SecondScreen extends StatefulWidget {
  SecondScreen({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _SecondScreenState createState() => _SecondScreenState();
}

class _SecondScreenState extends State<SecondScreen> {
  @override
  void initState() {
    super.initState();
    print("title");
    print(widget.title); // Ofc, it is null. I want it as 'Hello'!
  }

回答1:


Now, I found an approach. I'm sure there are better ways than this. First, I will override the onCreate method of MyFlutterActivity class. Then set the parameter in a global variable.

String title = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle extras = getIntent().getExtras();

    title = extras.getString("title");
}

@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
    GeneratedPluginRegistrant.registerWith(flutterEngine);

    new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL).setMethodCallHandler(((methodCall, result) -> {
        if (methodCall.method.equals("getBatteryLevel")) {

            result.success("batteryLevel"); // It returns string "batteryLevel".

        } else if (methodCall.method.equals("getTitle")) {

            result.success(title); // It returns string "Hello".

        } else {
            result.notImplemented();
        }
    }));
  }

Now, I can invoke the method in my initState of SecondScreen to get the title that passed completely from the native side.

  var title = await platformMethodChannel.invokeMethod('getTitle');


来源:https://stackoverflow.com/questions/65780859/fetch-arguments-in-flutter-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!