Advertisement
yudiwibisono

flutter_put

May 21st, 2023 (edited)
1,377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 2.26 KB | None | 0 0
  1. import 'package:flutter/material.dart';
  2. import 'package:http/http.dart' as http;
  3.  
  4. void main() => runApp(MaterialApp(home: MyApp()));
  5.  
  6. class MyApp extends StatefulWidget {
  7.   const MyApp({Key? key}) : super(key: key);
  8.   @override
  9.   MyAppState createState() => MyAppState();
  10. }
  11.  
  12. class MyAppState extends State<MyApp> {
  13.   late Future<int> respPost; //201 artinya berhasil
  14.   String url = "http://127.0.0.1:8000/tambah_mhs/";
  15.  
  16.   Future<int> insertData() async {
  17.     //data disimpan di body
  18.     final response = await http.post(Uri.parse(url), headers: <String, String>{
  19.       'Content-Type': 'application/json; charset=UTF-8'
  20.     }, body: """
  21.      {"nim": "13594022",
  22.      "nama": "Sandra Permana",
  23.      "id_prov": "12",
  24.      "angkatan": "2020",
  25.      "tinggi_badan": 190} """);
  26.     return response.statusCode; //sukses kalau 201
  27.   }
  28.  
  29.   @override
  30.   void initState() {
  31.     super.initState();
  32.     respPost = Future.value(0); //init
  33.   }
  34.  
  35.   @override
  36.   Widget build(BuildContext context) {
  37.     return MaterialApp(
  38.       title: 'My App',
  39.       home: Scaffold(
  40.         appBar: AppBar(
  41.           title: const Text('My App'),
  42.         ),
  43.         body: Center(
  44.             child: Column(
  45.           mainAxisSize: MainAxisSize.min,
  46.           children: [
  47.             ElevatedButton(
  48.               onPressed: () {
  49.                 setState(() {
  50.                   respPost = insertData();
  51.                 });
  52.               },
  53.               child: const Text('Klik Untuk Insert data (POST)'),
  54.             ),
  55.             Text("Hasil:"),
  56.             FutureBuilder<int>(
  57.                 future: respPost,
  58.                 builder: (context, snapshot) {
  59.                   if (snapshot.hasData) {
  60.                     if (snapshot.data! == 201) {
  61.                       return Text("Proses Insert Berhasil!");
  62.                     }
  63.                     if (snapshot.data! == 0) {
  64.                       return Text("");
  65.                     } else {
  66.                       return Text("Proses insert gagal");
  67.                     }
  68.                   }
  69.                   // default: loading spinner.
  70.                   return const CircularProgressIndicator();
  71.                 })
  72.           ],
  73.         )), //column center
  74.       ), //Scaffold
  75.     ); //Material APP
  76.   }
  77. }
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement