簡體   English   中英

如何使用 flutter_graphql 插件解析 flutter 中的 graphql 響應

[英]How to parse a graphql response in flutter using flutter_graphql plugin

我正在使用 graphql 突變發布數據。 我想要做的是解析響應數據並在我的 flutter 應用程序的小部件上使用。

我如何從 graphql 突變中獲取解析響應數據這是我的代碼

`

class RegisterService {
  final String name, phone, email, password;
  final VoidCallback onCompleted, onError;
  RegisterService({
    this.name = "",
    this.phone = "",
    this.email = "",
    this.password = "",
    required this.onCompleted,
    required this.onError,
  });

  Future<Object?> sendData() async {
    String addData = """
mutation signup(\$signupInput: SignupInput!) {
  signup(signupInput: \$signupInput) {
    success
    message
    phone
  }
}
""";
    final variable = {
      "signupInput": {
        "name": name,
        "phone": phone,
        "email": email,
        "password": password,
      }
    };
    debugPrint("SendingData");

    QueryResult mutationResult = await qlclient.mutate(MutationOptions(
      document: gql(addData),
      variables: variable,
      onCompleted: (_) {
        onCompleted();
      },
      onError: (_) => onError(),
    ));


    debugPrint("${mutationResult.data?["signup"]["message"]}");
    return mutationResult;
  }
}

`

這是 function`

  void buttonPressed() async {
    changeStatus(true);
    debugPrint("$_isLoading");
    Timer(Duration(seconds: 3), () {
      if (formKey.currentState!.validate()) {
        debugPrint("Successful");
      } else {
        autoValidate = autovalidateModeOnUser;
      }
      var utils =  RegisterService(
          onError: () {},
          onCompleted: (() {
            changeStatus(false);
          }),
          name: nameTextEditingController.text.trim(),
          phone: ("09" + "${phoneTextEditingController.text.trim()}"),
          password: phoneTextEditingController.text.trim(),
          email: emailTextEditingController.text.trim(),
          );
      var res = utils.sendData();
  
      debugPrint("${res}");
      globalKeyScaffoldMessengerState.currentState
          ?.showSnackBar(mySnackBar("utils.sendData()."));
    });

    notifyListeners();
  }

`

我想獲得響應並在我的小部件上使用它。 我正在使用 flutter_graphql 插件。

這是 json 結果。

`

{
  "data": {
    "signup": {
      "success": true,
      "message": "Code sent to your phone successfully!",
    }
  }
}

`

  1. 從該站點將響應 json 轉換為 dart: https://javiercbk.github.io/json_to_dart/

  2. ClassName classObject = ClassName.fromJson(jsonEncode(mutationResult.data));

  3. 您可以這樣訪問: classObject.data.signup等等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM