Skip to content

Commit

Permalink
Fix/cors error pubdev example (#2286)
Browse files Browse the repository at this point in the history
  • Loading branch information
PapiHack committed Mar 10, 2023
1 parent bf6e79c commit 829bf27
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
27 changes: 25 additions & 2 deletions examples/pub/lib/pub_repository.dart
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:pubspec_parse/pubspec_parse.dart';

part 'pub_repository.freezed.dart';
part 'pub_repository.g.dart';

class PubRepository {
PubRepository() {
_configureDio();
}

static const _scheme = 'https';
static const _host = 'pub.dartlang.org';

final dio = Dio();

Future<List<Package>> getPackages({
Expand Down Expand Up @@ -56,7 +60,6 @@ class PubRepository {
required String packageName,
CancelToken? cancelToken,
}) async {
final dio = Dio();
final uri = Uri(
scheme: _scheme,
host: _host,
Expand Down Expand Up @@ -163,6 +166,12 @@ class PubRepository {
final packageResponse = LikedPackagesResponse.fromJson(response.data!);
return packageResponse.likedPackages.map((e) => e.package).toList();
}

void _configureDio() {
if (kIsWeb) {
dio.interceptors.add(PubProxyInterceptor());
}
}
}

const userToken = '';
Expand Down Expand Up @@ -258,3 +267,17 @@ class PubSearchResponse with _$PubSearchResponse {
factory PubSearchResponse.fromJson(Map<String, Object?> json) =>
_$PubSearchResponseFromJson(json);
}

// A custom interceptor that proxies requests to a cors-proxy server
// in order to workaround the CORS issue on web platform.
class PubProxyInterceptor extends Interceptor {
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
super.onRequest(
options.copyWith(
path: 'https://api.codetabs.com/v1/proxy/?quest=${options.path}',
),
handler,
);
}
}
6 changes: 5 additions & 1 deletion examples/pub/lib/pub_ui/appbar.dart
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

class PubAppbar extends StatelessWidget implements PreferredSizeWidget {
const PubAppbar({super.key});
static const _webProxy = 'https://api.codetabs.com/v1/proxy';
static const _dartLogoURL =
'https://pub.dev/static/hash-6pt3begn/img/pub-dev-logo.svg';

@override
Widget build(BuildContext context) {
return AppBar(
backgroundColor: const Color(0xFF1c2834),
title: SvgPicture.network(
'https://pub.dev/static/hash-6pt3begn/img/pub-dev-logo.svg',
kIsWeb ? '$_webProxy/?quest=$_dartLogoURL' : _dartLogoURL,
width: 150,
),
);
Expand Down

0 comments on commit 829bf27

Please sign in to comment.