-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
Copy pathmethod_channel_demo.dart
92 lines (85 loc) · 3.01 KB
/
method_channel_demo.dart
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:platform_channels/src/counter_method_channel.dart';
/// The widget demonstrates how to use [MethodChannel] to invoke platform methods.
/// It has two [FilledButton]s to increment and decrement the value of
/// [count], and a [Text] widget to display its value.
class MethodChannelDemo extends StatefulWidget {
const MethodChannelDemo({super.key});
@override
State<MethodChannelDemo> createState() => _MethodChannelDemoState();
}
class _MethodChannelDemoState extends State<MethodChannelDemo> {
int count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('MethodChannel Demo'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Value of count is $count',
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(
height: 16,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
// Whenever users press the FilledButton, it invokes
// Counter.increment method to increment the value of count.
FilledButton.icon(
onPressed: () async {
try {
final value = await Counter.increment(counterValue: count);
setState(() => count = value);
} catch (error) {
if (!context.mounted) return;
showErrorMessage(
context,
(error as PlatformException).message!,
);
}
},
icon: const Icon(Icons.add),
label: const Text('Increment'),
),
// Whenever users press the FilledButton, it invokes
// Counter.decrement method to decrement the value of count.
FilledButton.icon(
onPressed: () async {
try {
final value = await Counter.decrement(counterValue: count);
setState(() => count = value);
} catch (error) {
if (!context.mounted) return;
showErrorMessage(
context,
(error as PlatformException).message!,
);
}
},
icon: const Icon(Icons.remove),
label: const Text('Decrement'),
)
],
)
],
),
);
}
void showErrorMessage(BuildContext context, String errorMessage) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(errorMessage),
),
);
}
}