forked from flutter/samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
method_channel_demo.dart
87 lines (81 loc) · 2.78 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
// 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:platform_channels/src/counter_method_channel.dart';
/// The widget demonstrates how to use [MethodChannel] to invoke platform methods.
/// It has two [ElevatedButton]s to increment and decrement the value of
/// [count], and a [Text] widget to display its value.
class MethodChannelDemo extends StatefulWidget {
@override
_MethodChannelDemoState 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.headline5,
),
SizedBox(
height: 16,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
// Whenever users press the ElevatedButton, it invokes
// Counter.increment method to increment the value of count.
ElevatedButton.icon(
onPressed: () async {
try {
final value = await Counter.increment(counterValue: count);
setState(() => count = value);
} catch (error) {
showErrorMessage(
context,
error.message as String,
);
}
},
icon: Icon(Icons.add),
label: Text('Increment'),
),
// Whenever users press the ElevatedButton, it invokes
// Counter.decrement method to decrement the value of count.
ElevatedButton.icon(
onPressed: () async {
try {
final value = await Counter.decrement(counterValue: count);
setState(() => count = value);
} catch (error) {
showErrorMessage(
context,
error.message as String,
);
}
},
icon: Icon(Icons.remove),
label: Text('Decrement'),
)
],
)
],
),
);
}
void showErrorMessage(BuildContext context, String errorMessage) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(errorMessage),
),
);
}
}