flutter laravel api post

note: 아직 예외 처리 전 상황

참고 쿡북

laravel backend

Route::post('/post-here', function(Request $request) {
    // validation
    $validatedData = $request->validate([
        'name' => 'required|string|max:255',
        'description' => 'required|string|max:255',
    ]);

    $paymentMethod = PaymentMethod::create([
        'name' => $validatedData['name'],
        'description' => $validatedData['description'],
    ]);

    print($paymentMethod);

    return response()->json([
    ], 201);

});

201 status code를 넣고 response는 json로 변환해서 보낸다.
그런데...
post response json

{
    "name": "here",
    "description": "haha",
    "updated_at": "2022-04-18T12:05:50.000000Z",
    "created_at": "2022-04-18T12:05:50.000000Z",
    "id": 67
}[]

이 이렇게 나온다. 마지막에 불필요한 []이 추가 된다.
왜 그런지 모르고 어떻게 해결 할 줄 아직 몰라,
이건 flutter에서 받을 때 .replace()를 사용 해서 없애줄 것 이다.

full code

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<Album> createAlbum(String name, description) async {
  final response = await http.post(
    Uri.parse('<URL HERE>'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'name': name,
      'description': description,
    }),
  );

  if (response.statusCode == 201) {
    // If the server did return a 201 CREATED response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body.replaceAll(r'[]', r''))); // 임시 방편으로
  } else {
    // If the server did not return a 201 CREATED response,
    // then throw an exception.
    throw Exception('Failed to create album.');
  }
}

class Album {
  final String name;
  final String description;

  const Album({required this.name, required this.description});

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      name: json['name'],
      description: json['description'],
    );
  }
}

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  final TextEditingController _controller1 = TextEditingController();
  final TextEditingController _controller2 = TextEditingController();
  Future<Album>? _futureAlbum;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Create Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Create Data Example'),
        ),
        body: Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.all(8.0),

          // input이 안/들어가 있으면 처리
          child: (_futureAlbum == null) ? buildColumn() : buildFutureBuilder(),
        ),
      ),
    );
  }

  Column buildColumn() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        TextField(
          controller: _controller1,
          decoration: const InputDecoration(hintText: 'Enter Title'),
        ),
        TextField(
          controller: _controller2,
          decoration: const InputDecoration(hintText: 'Enter Title'),
        ),
        ElevatedButton(
          onPressed: () {
            setState(() {
              _futureAlbum = createAlbum(_controller1.text, _controller2.text);
            });
          },
          child: const Text('Create Data'),
        ),
      ],

    );
  }

  // 여기는 보여지는 곳
  FutureBuilder<Album> buildFutureBuilder() {
    return FutureBuilder<Album>(
      future: _futureAlbum,
      builder: (context, snapshot) {
        print(snapshot);
        if (snapshot.hasData) {
          print(snapshot.data);
          return Text(snapshot.data!.name);
          // return Text('yes!');

        } else if (snapshot.hasError) {
          return Text('${snapshot.error}');
        }

        return const CircularProgressIndicator();
      },
    );
  }
}

좋은 웹페이지 즐겨찾기