-
Notifications
You must be signed in to change notification settings - Fork 7.7k
/
Copy pathsign_in_http.dart
112 lines (98 loc) · 3.39 KB
/
sign_in_http.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:json_annotation/json_annotation.dart';
part 'sign_in_http.g.dart';
@JsonSerializable()
class FormData {
String? email;
String? password;
FormData({this.email, this.password});
factory FormData.fromJson(Map<String, dynamic> json) =>
_$FormDataFromJson(json);
Map<String, dynamic> toJson() => _$FormDataToJson(this);
}
class SignInHttpDemo extends StatefulWidget {
final http.Client? httpClient;
const SignInHttpDemo({this.httpClient, super.key});
@override
State<SignInHttpDemo> createState() => _SignInHttpDemoState();
}
class _SignInHttpDemoState extends State<SignInHttpDemo> {
FormData formData = FormData();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sign in Form')),
body: Form(
child: Scrollbar(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
children: [
...[
TextFormField(
autofocus: true,
textInputAction: TextInputAction.next,
decoration: const InputDecoration(
filled: true,
hintText: 'Your email address',
labelText: 'Email',
),
onChanged: (value) {
formData.email = value;
},
),
TextFormField(
decoration: const InputDecoration(
filled: true,
labelText: 'Password',
),
obscureText: true,
onChanged: (value) {
formData.password = value;
},
),
TextButton(
child: const Text('Sign in'),
onPressed: () async {
// Use a JSON encoded string to send
var result = await widget.httpClient!.post(
Uri.parse('https://example.com/signin'),
body: json.encode(formData.toJson()),
headers: {'content-type': 'application/json'},
);
_showDialog(switch (result.statusCode) {
200 => 'Successfully signed in.',
401 => 'Unable to sign in.',
_ => 'Something went wrong. Please try again.',
});
},
),
].expand((widget) => [widget, const SizedBox(height: 24)]),
],
),
),
),
),
);
}
void _showDialog(String message) {
showDialog<void>(
context: context,
builder:
(context) => AlertDialog(
title: Text(message),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () => Navigator.of(context).pop(),
),
],
),
);
}
}