I have profile data in the form of a Map. I need to pass them to the platform and return them back with a modified update date using the platform channel. How can I change the update date and revert back? The data should be updated on clicking the ElevatedButton. My Flutter Page:
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
static const platform = MethodChannel('samples.flutter.dev/profile');
late Map<String, String> _profile = {
'name': 'myName',
'date of birth': 'myDate',
'profile update date': '20.06.2022',
};
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(_profile['name'] ?? ''),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(_profile['date of birth'] ?? ''),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(_profile['profile update date'] ?? ''),
],
),
const SizedBox(height: 30),
ElevatedButton(
child: const Text('Get Update Profile'),
onPressed: _getUpdateProfile,
),
],
),
),
);
}
Future<void> _getUpdateProfile() async {
Map<String, String> profile;
try {
final int result = await platform.invokeMethod('updateProfile');
profile = {
'profile update date': '$result',
};
} on PlatformException catch (e) {
profile = {
'profile update date': '${e.message}',
};
}
setState(() {
_profile = profile;
});
}
}
My Kotlin code:
class MainActivity : FlutterActivity() {
private val CHANNEL = "samples.flutter.dev/profile"
}
CodePudding user response:
Hey you can return data from method channel
like this -
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), "my_channel_name")
.setMethodCallHandler((methodCall, result) -> {
if (methodCall.method.equals("returnStringDataList")) {
// Return your List here.
List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
result.success(list);
}
});
void getDataList() async {
var channel = MethodChannel('my_channel_name');
List<String>? list = await channel.invokeListMethod<String>('returnStringDataList');
print(list); // [A, B, C]
}