How to redirect a request in Dart/shelf?


I’m using shelf in Dart to setup a simple web server. How can I redirect a request from / to /oauth2callback in the example below?

I have found this method, but somehow I cannot compile the code even though I import dart:io.

import 'dart:io';

import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router/shelf_router.dart';

final router = Router()
  ..get('/', rootHandler)
  ..get('/oauth2callback', oauth2callback);

Response rootHandler(Request req) {
  return Response.ok('Hello, World!\n');

Response oauth2callback(Request request) {
  return Response.ok('Redirected!\n');


void main(List<String> args) async {
  final _handler = Pipeline().addMiddleware(logRequests()).addHandler(router);
  final server = await serve(_handler, '', 8080);
  print('Server listening on port ${server.port}');


You could send a 302 response like this:

Response rootHandler(Request request) {
  Map<String,String> headers = {'location':'/oauth2callback'};
  return Response(302,headers:headers);

Answered By – user697576

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *