POST
๐ฌ ์๋ฒ์ ์๊ตฌํ๋ ํฌ๋งท์ ๋ง์ถฐ ์๋ฒ๋ก ๋ฐ์ดํฐ๋ฅผ ์ ์กํ๊ณ , ๋์ ๋ฐ๋ผ ์๋ฒ์์ ํ์ ํ๋ Response๋ฅผ ๋ฐ๋ ์์
์์
๐ฌ ๋ ๊ฐ์ ์ ๋ ฅ์ ๋ฐ์ ์ ์๋ TextField
๐ฌ ๊ฐ์ ์ ๋ ฅ ํ FloatingButton์ ํด๋ฆญ ์ ์น ์๋ฒ์ ์ ๋ ฅํ ๊ฐ์ ์ง์ ํ ํฌ๋งท์ผ๋ก post ํ response๋ฅผ ๋ฐ์์ ํ๋ฉด์ ๋์์ค๋ค.
๋ชจ๋ธ ํด๋์ค ๋ง๋ค๊ธฐ
๐ฌ response๋ก ๋ฐ์ Json ๋ฐ์ดํฐ์ ํฌ๋งท์ ๋ง๋ ์์ ๋ฐ์ดํฐ๋ฅผ ํ๋ฉด ์ผํธ์ ์ ์ผ๋ฉด ์ค๋ฅธํธ์ Json์์ String๊น์ง์ ์ธ์ฝ๋, ๋์ฝ๋ ์ฝ๋๊ฐ ํฌํจ๋ ํด๋์ค๊ฐ ๋ง๋ค์ด์ง๋ฉฐ, ์ด๋ฅผ ์ฌ์ฉํ์ฌ ๋ชจ๋ธ ํด๋์ค๋ฅผ ๋ง๋ ๋ค.
์ฝ๋ ์์ฑํ๊ธฐ
main.dart
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
Future<UserModel> createUser(String name, String jobTitle) async {
const String apiUrl = "https://reqres.in/api/users";
// post๋ฅผ ๋ณด๋ด๊ณ await๋ก response๋ฅผ ๋ฐ์์จ ๊ฒ์ response์ ๋ฃ๋๋ค.
final response = await http.post(apiUrl, body: {
"name": name,
"job": jobTitle
});
if (response.statusCode == 201) {
final String responseString = response.body;
return userModelFromJson(responseString);
} else {
return throw Exception('Error');
}
}
class _MyHomePageState extends State<MyHomePage> {
late UserModel _user = UserModel(name: "", job: "", id: "", createdAt: DateTime.now());
final TextEditingController nameController = TextEditingController();
final TextEditingController jobController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('HTTP Test'),
),
body:Container(
padding: const EdgeInsets.all(32),
child: Column(
children: <Widget>[
TextField(
controller: nameController,
),
TextField(
controller: jobController,
),
const SizedBox(height: 32,),
Text(
"User Name : ${_user.name}\n"
"User Job : ${_user.job}\n"
"User Id : ${_user.id}\n"
"Create Time : ${_user.createdAt.toIso8601String()}"
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
final String name = nameController.text;
final String jobTitle = jobController.text;
final UserModel user = await createUser(name, jobTitle);
setState(() {
_user = user;
});
},
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
์ถ๊ฐ ์ง์
response code
200 (์ฑ๊ณต) : ์๋ฒ๊ฐ ์์ฒญ์ ์ ๋๋ก ์ฒ๋ฆฌํ๋ค๋ ์๋ฏธ. ์ฃผ๋ก ์๋ฒ๊ฐ ์์ฒญ๋ฐ์ ํ์ด์ง๋ฅผ ์ ๊ณตํ๋ค๋ ์๋ฏธ๋ก ์ฐ์ธ๋ค.
201 (์์ฑ๋จ) : ์ฑ๊ณต์ ์ผ๋ก ์์ฒญ๋์์ผ๋ฉฐ, ์๋ฒ๊ฐ ์ ๋ฆฌ์์ค๋ฅผ ์์ฑํ๋ค๋ ์๋ฏธ๋ก ์ฐ์ธ๋ค.
'Flutter > Concept' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ Flutter ] ์ด๋ฏธ์ง (0) | 2022.02.22 |
---|---|
[ Flutter ] BottomNavigationBar (0) | 2022.02.19 |
[ Flutter ] Web ๋ฐฐํฌ using GitHub (0) | 2022.01.07 |
[ Flutter ] ํ๋ฉด ์ด๋ (0) | 2021.12.29 |
[ Flutter ] ์ฟ ํผํฐ๋ ธ ๋์์ธ (0) | 2021.12.29 |