我已阅读此https://github.com/flutter/flutter/wiki/Add-Flutter-to-existing-apps。
我的问题是将数据从现有的原生 android 应用程序传递到 flutter 模块(例如:令牌、用户名...等)。所以,我想问一下,有没有什么办法可以在现有的native app中的native code和flutter module中的code之间传递数据?
比如有两个页面,A和B,A是用Java代码写的,B嵌入了flutter view,我在B中没有找到从A传数据到flutter view的方法。
public class TwoActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.two_activity);
//this params passed from HomeActivity
String params = getIntent().getStringExtra("params");
FrameLayout rootView = findViewById(R.id.container);
View flutterView = Flutter.createView(this, getLifecycle(), "service");
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
rootView.addView(flutterView, layoutParams);
}
}
Run Code Online (Sandbox Code Playgroud)
这是 main.dart
void main() => runApp(chooseWidget(window.defaultRouteName));
Widget chooseWidget(String route) {
switch(route) {
case 'service':
return MyFlutterView();
}
}
class MyFlutterView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
static const platform = const MethodChannel('samples.flutter.dev/start');
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: Column(
children: <Widget>[
Text(
'this is a flutter page',
style: TextStyle(
fontSize: 14,
color: Colors.blue
),
),
FlatButton(
onPressed: () {
platform.invokeMethod('startActivity');
},
child: Text('go native page'),
color: Colors.purple,
highlightColor: Colors.deepPurple,
)
],
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
-------------------------->2019.7.18编辑<-- ------------
Thank you for your help. I found the answer.
1?BasicMessageChannel?use this to pass string or other object.
2?MethodChannel?use this to method invocation
3?EventChannel: use this to event streams
Run Code Online (Sandbox Code Playgroud)
您可以为此使用方法通道
private static final String CHANNEL = "AndySample/test";
FlutterEngine flutterEngine=new FlutterEngine(this);
flutterEngine.getDartExecutor().executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
);
FlutterEngineCache
.getInstance()
.put("my_engine_id", flutterEngine);
flutterEngine.getNavigationChannel().setInitialRoute("/");
MethodChannel mc=new
MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(),CHANNEL);
mc.setMethodCallHandler((methodCall, result) ->
{
if(methodCall.method.equals("test"))
{
result.success("Hai from android and this is the data yopu sent me "+ methodCall.argument("data"));
//Accessing data sent from flutter
}
else
{
Log.i("new method came",methodCall.method);
}
}
);
Run Code Online (Sandbox Code Playgroud)
使用此博客了解更多信息
https://medium.com/@andymobitec/flutter-sending-data- Between-android-and-flutter-1e0693fbae64