Skip to content

Commit

Permalink
mutation
Browse files Browse the repository at this point in the history
  • Loading branch information
mirmoktadir committed Jun 12, 2023
1 parent de26fa4 commit 77788ce
Show file tree
Hide file tree
Showing 4 changed files with 142 additions and 96 deletions.
82 changes: 62 additions & 20 deletions lib/app/modules/Graphql/controllers/graphql_controller.dart
Original file line number Diff line number Diff line change
@@ -1,42 +1,84 @@
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:getx_standard/app/components/custom_snackbar.dart';
import 'package:getx_standard/app/service/REST/base_controller.dart';

import '../../../service/graphQL/graphql_service.dart';

class GraphQLController extends GetxController with BaseController {
final GraphQLService graphQLService = GraphQLService();
final albumList = RxList<dynamic>();
_albumQuery() {
return """
query Query {
albums(options:{paginate:{page:2,limit:10}}){
data{
title
photos{
data{
thumbnailUrl
}
}
final userList = RxList<dynamic>();
RxString mutationResult = "".obs;

///////////////////// QUERY /////////////////////////
Future<void> getAlbums() async {
try {
showLoading();
// Build your query string
const query = """
query Query{
users{
id
name
email
todos{
description
}
}
}
""";

// Perform the query
final result = await graphQLService.performQuery(query);
userList.value = List.from(result["users"]);
hideLoading();
// Handle the result
// Update the UI or perform other actions with the result
} catch (error) {
// Handle the exception
hideLoading();
CustomSnackBar.showCustomErrorSnackBar(
title: "Error!", message: error.toString());
if (kDebugMode) {
print('Error: $error');
}
// Show a snackbar or dialog to inform the user about the error
}
}

getAlbums() async {
//////////////////////// MUTATION ///////////////////////////
Future<void> updateTodo() async {
try {
showLoading();
var result = await graphQLService.performQuery(_albumQuery());
albumList.value = List.from(result.data["albums"]["data"]);
if (kDebugMode) {
print(result.data);
// Build your mutation or query string
const mutation = '''
mutation {
updateTodo(input:{id:"Hello World",description:"Hello World"}){
id
description
done
}
}
''';

// Perform the mutation
final result = await graphQLService.performMutation(mutation);
mutationResult.value = result.toString();
hideLoading();
} catch (e) {
showLoading();
print(e);
// Handle the result
// Update the UI or perform other actions with the result
} catch (error) {
// Handle the exception
hideLoading();
CustomSnackBar.showCustomErrorSnackBar(
title: "Error!", message: error.toString());
if (kDebugMode) {
print('Error: $error');
}
// Show a snackbar or dialog to inform the user about the error
}
}

Expand Down
105 changes: 58 additions & 47 deletions lib/app/modules/Graphql/views/graphql_view.dart
Original file line number Diff line number Diff line change
Expand Up @@ -28,58 +28,69 @@ class GraphQLView extends GetView<GraphQLController> {
radius: const Radius.circular(100),
thickness: 5,
interactive: true,
child: ListView.separated(
itemCount: controller.albumList.length,
physics: const BouncingScrollPhysics(),
padding: EdgeInsets.zero,
separatorBuilder: (_, __) => SizedBox(
height: 20.h,
),
itemBuilder: (ctx, index) => Container(
padding: const EdgeInsets.all(5),
width: double.infinity,
color: theme.canvasColor,
child: Center(
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius:
BorderRadius.all(Radius.circular(10.r)),
boxShadow: [
BoxShadow(
color: theme.primaryColor.withOpacity(.3),
blurRadius: 7.0,
spreadRadius: 4,
offset: const Offset(0, 3),
)
]),
child: Column(
children: [
Text(
controller.albumList[index]["title"] ?? "",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: MyFonts.headline6TextSize,
fontWeight: FontWeight.w500,
color: theme.primaryColor,
),
),
SizedBox(height: 10.h),
SizedBox(
height: 150.h,
width: 150.w,
child: Image.network(
controller.albumList[index]["photos"]["data"]
[0]["thumbnailUrl"],
fit: BoxFit.cover,
child: Column(
children: [
SizedBox(
width: 150.w,
child: ElevatedButton(
onPressed: () async {
await controller.updateTodo();
},
child: const Text("Run mutation")),
),
controller.mutationResult.isEmpty
? const SizedBox()
: Padding(
padding: EdgeInsets.symmetric(vertical: 20.h),
child: Text(
"RESULT :${controller.mutationResult.value}"),
),
Expanded(
child: ListView.separated(
itemCount: controller.userList.length,
physics: const BouncingScrollPhysics(),
padding: EdgeInsets.zero,
separatorBuilder: (_, __) => SizedBox(
height: 20.h,
),
itemBuilder: (ctx, index) => Container(
padding: const EdgeInsets.all(5),
width: double.infinity,
color: theme.canvasColor,
child: Center(
child: Container(
width: double.infinity,
height: 50,
decoration: BoxDecoration(
color: Colors.white,
borderRadius:
BorderRadius.all(Radius.circular(10.r)),
boxShadow: [
BoxShadow(
color:
theme.primaryColor.withOpacity(.3),
blurRadius: 7.0,
spreadRadius: 4,
offset: const Offset(0, 3),
)
]),
child: Center(
child: Text(
controller.userList[index]["name"] ?? "",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: MyFonts.headline6TextSize,
fontWeight: FontWeight.w500,
color: theme.primaryColor,
),
),
),
),
SizedBox(height: 10.h),
],
),
),
),
),
),
],
),
),
),
Expand Down
4 changes: 2 additions & 2 deletions lib/app/service/graphQL/graphql_config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import 'package:graphql_flutter/graphql_flutter.dart';

class GraphQLConfig {
static HttpLink httpLink = HttpLink(
"https://graphqlzero.almansi.me/api",
);
// "https://graphqlzero.almansi.me/api",
"https://api.mocki.io/v2/c4d7a195/graphql");

GraphQLClient graphqlClient() => GraphQLClient(
cache: GraphQLCache(),
Expand Down
47 changes: 20 additions & 27 deletions lib/app/service/graphQL/graphql_service.dart
Original file line number Diff line number Diff line change
@@ -1,43 +1,36 @@
import 'package:get/get.dart';
import 'package:getx_standard/app/service/graphQL/graphql_config.dart';
import 'package:graphql_flutter/graphql_flutter.dart';

import 'graphql_config.dart';

class GraphQLService extends GetxService {
GraphQLConfig graphQLConfig = GraphQLConfig();

Future<GraphQLResult> performQuery(String query) async {
final options = QueryOptions(document: gql(query));
final result = await graphQLConfig.graphqlClient().query(options);
return _handleResult(result);
}
Future<dynamic> performMutation(String mutation) async {
final mutationOptions = MutationOptions(
document: gql(mutation),
);

Future<GraphQLResult> performMutation(String mutation) async {
final options = MutationOptions(document: gql(mutation));
final result = await graphQLConfig.graphqlClient().mutate(options);
return _handleResult(result);
}
final result = await graphQLConfig.graphqlClient().mutate(mutationOptions);

GraphQLResult _handleResult(QueryResult result) {
if (result.hasException) {
final graphqlError = result.exception?.graphqlErrors.first;
throw GraphQLError(graphqlError!.message);
} else {
return GraphQLResult(result.data);
throw result.exception!;
}
}
}

class GraphQLError implements Exception {
final String message;
return result.data;
}

GraphQLError(this.message);
Future<dynamic> performQuery(String query) async {
final queryOptions = QueryOptions(
document: gql(query),
);

@override
String toString() => 'GraphQLError: $message';
}
final result = await graphQLConfig.graphqlClient().query(queryOptions);

class GraphQLResult {
final dynamic data;
if (result.hasException) {
throw result.exception!;
}

GraphQLResult(this.data);
return result.data;
}
}

0 comments on commit 77788ce

Please sign in to comment.