【发布时间】:2021-01-10 00:55:03
【问题描述】:
我正在尝试学习如何将 rails 与 graphql 结合使用,通过开发一个简单的应用程序来创建 rails API,该应用程序仅从数据库中检索文本(在我的情况下为引号)并将其显示在屏幕上。我使用颤振作为前端和使用graphql 作为后端的rails。后端部分很容易创建,因为我已经掌握了一些 Rails 知识,但前端部分是我的新手,我试图弄清楚如何访问我通过颤振创建的 graphql 查询以获取需要的数据显示出来。
下面是我目前拥有的flutter代码(部分改编自How to build a mobile app from scratch with Flutter and maybe Rails?)。
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Quote> fetchQuote() async {
final response =
await http.get('http://10.0.2.2:3000/graphql?query={quote{text}}');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON.
return Quote.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load quote');
}
}
class Quote {
final String text;
Quote({this.text});
factory Quote.fromJson(Map<String, dynamic> json) {
return Quote(
text: json['text']
);
}
}
void main() => runApp(MyApp(quote: fetchQuote()));
class MyApp extends StatelessWidget {
final Future<Quote> quote;
MyApp({this.quote});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Quote>(
future: quote,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.text);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
),
),
);
}
}
我自己已经发现这段代码错误的一些明显原因是,当我的代码发送获取请求时,graphql 服务器期望查询的发布请求,但这是我的问题。 如何在 Flutter 中向我的 graphql 服务器发送一个发布请求以检索数据?我尝试访问的查询是我的 Flutter 代码中“?query=”之后的查询。 p>
【问题讨论】:
-
最简单的事情,请查看flutter.dev/docs/cookbook/networking/send-data 了解如何发布 http.post。不太容易,您的服务器似乎配置不正确。获取数据时使用 Get,更改某些内容时使用 Post。看起来您正在正确地尝试获取我可以看到的代码,所以我的猜测是服务器错误。
标签: api flutter graphql http-post