问题
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