1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| void main() => runApp(MethodChannelDemo()); class MethodChannelDemo extends StatefulWidget { @override _MethodChannelDemoState createState() => _MethodChannelDemoState(); } class _MethodChannelDemoState extends State<MethodChannelDemo> { var channel = MethodChannel('com.example.androidflutter.MethodChannelDemo');
var _data; var _nativeData; @override void initState() { super.initState(); channel.setMethodCallHandler((call) async { setState(() { _nativeData = call.arguments['count']; }); }); }
@override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text("Flutter MethodChannel")), body: Column( children: [ SizedBox(height: 50,), RaisedButton( child: Text('发送数据到原生'), onPressed: () async { var result = await channel .invokeMethod('sendData', {'name': '张三', 'age': 18}); var name = result['name']; var age = result['age']; setState(() { _data = '$name,$age'; }); }, ), Text('原生返回数据:$_data'), Text('原生主动发送数据:$_nativeData') ], ), ), ); } }
|