我已经读过这个https://github.com/flutter/flutter/wiki/Add-Flutter-to-existing-apps。
我的问题是将数据从现有的本机android应用传递到flutter模块(例如:令牌,用户名...等)。因此,我想问一下是否存在通过现有本地应用程序中的本地代码和Flutter模块中的代码之间传递数据的方法?
例如,有两个页面,A和B,A是用Java代码编写的,B嵌入了flutter视图,我没有找到将数据从A传递到B中flutter视图的方法。
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);
}
}
这是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,
)
],
),
);
}
}
-------------------------->在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
答案 0 :(得分:1)
通过平台渠道{{3}}
与本机端进行通信基本上,您来回传递json字符串。
答案 1 :(得分:0)
您可以为此使用方法频道
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);
}
}
);
使用此博客了解更多信息
https://medium.com/@andymobitec/flutter-sending-data-between-android-and-flutter-1e0693fbae64