flutter laravel api post
6266 ワード
注意:例外処理前の状態
リファレンスマニュアル
でも….
post response json
なぜか、どうやって解決するか分からず、
これはflufで受け取ったときに
リファレンスマニュアル
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を入力し、応答を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
}[]
こうして出てきた最後に、不要な[]
が追加されます.なぜか、どうやって解決するか分からず、
これはflufで受け取ったときに
.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();
},
);
}
}
Reference
この問題について(flutter laravel api post), 我々は、より多くの情報をここで見つけました https://velog.io/@hur-kyuh-leez/flutter-laravel-api-postテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol