Home > OS >  error when bring data DioError [DioErrorType.response]: Http status error [401]
error when bring data DioError [DioErrorType.response]: Http status error [401]

Time:07-21

I have an error while using API with Dio i bring the data from the api with url and key , queries , the data should show in the debug console when i press the icon of the floating bottom but it is not showing to and says ''DioError [DioErrorType.response]: Http status error [401]''

enter image description here

this is the dio helper code


class DioHelper {
  static Dio? dio;

  static init() {
    dio = Dio(
      BaseOptions(
        baseUrl: 'https://newsapi.org/',
        receiveDataWhenStatusError: true,
      ),
    );
  }

  //this method is to get data from link
  static Future<Response> getdata({
    required String
        url, // is the path that i will move in it will change while bring data so i need to make a parameter form it so when it is changed i see this change
    required Map<String, dynamic> query,
  }) async {
    return await dio!.get(
      url,
      queryParameters: query,
    );
  }
}

this one is for the screen I did to show the data


import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:notes/layout/news_layout/cubit/cubit.dart';
import 'package:notes/layout/news_layout/cubit/states.dart';
import 'package:notes/shared/networking/remote/dio_helper.dart';

class NewsLayout extends StatelessWidget {
  const NewsLayout({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (BuildContext context) => NewsCubit(),
      child: BlocConsumer<NewsCubit, NewsStates>(
        listener: (context, state) {},
        builder: (context, state) {
          NewsCubit cubit = NewsCubit.get(context);

          return Scaffold(
            appBar: AppBar(
              title: const Text(
                'News App',
              ),
              actions: [
                IconButton(
                  onPressed: () {},
                  icon: const Icon(
                    Icons.search,
                  ),
                ),
              ],
            ),
            body: cubit.screens[cubit.currentIndex],
            floatingActionButton: FloatingActionButton(
              onPressed: () {
                DioHelper.getdata(
                  url: 'v2/top-headlines',
                  query: {
                    'country': 'eg',
                    'category': 'business',
                    'piKey':
                        '65f7f556ec76449fa7dc7c0069f040ca', //a6efe67bc3564f539b6fdbdf9a830574
                  },
                ).then((value) {
                  print(value.data.toString()); //['articles'][0]['title']
                }).catchError((error) {
                  print('error when bring data ${error.toString()}');
                });
              },
              child: const Icon(Icons.add),
            ),
            bottomNavigationBar: BottomNavigationBar(
              currentIndex: cubit.currentIndex,
              onTap: (index) {
                cubit.changeIndex(index);
              },
              items: cubit.bottomItems,
            ),
          );
        },
      ),
    );
  }
}

this one is the main

import 'package:flutter/services.dart';
import 'package:notes/layout/news_layout/news_layout.dart';
import 'package:notes/shared/networking/remote/dio_helper.dart';

void main() {
  DioHelper.init(); // this one here is to create tje dio object
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        scaffoldBackgroundColor: Colors.white,
        appBarTheme: const AppBarTheme(
          systemOverlayStyle: SystemUiOverlayStyle(
            // control the status bar color and icons color in ur mobile
            statusBarColor: Colors.white,
            statusBarIconBrightness: Brightness
                .dark, // use light when ur status color is not white otherwise use dark
          ),
          backgroundColor: Colors.white,
          elevation: 0.0,
          titleTextStyle: TextStyle(
            color: Colors.black,
            fontSize: 20.0,
            fontWeight: FontWeight.bold,
          ),
          iconTheme: IconThemeData(
            color: Colors.black,
          ),
        ),
        floatingActionButtonTheme: const FloatingActionButtonThemeData(
          backgroundColor: Colors.deepOrange,
        ),
        bottomNavigationBarTheme: const BottomNavigationBarThemeData(
          type: BottomNavigationBarType.fixed,
          selectedItemColor: Colors.deepOrange,
          elevation: 60.0,
        ),
      ),
      home: const NewsLayout(),
    );
  }
}

CodePudding user response:

You have to change piKey to apiKey. There is typo mistake

CodePudding user response:

the init() in DioHelper does not call, I recommend that change your Helper class to this one:

class DioHelper {
  static Dio get defaultApiClient => ApiClientBuilder()
      .ofUrl(BASE_URL)
      .setDefaultHeader()
      .addInterceptor(CheckNetworkInterceptor())
      .addInterceptor(ErrorInterceptor())
      .create();
}

class ApiClientBuilder {
  static const int defaultTimeout = 15000;

  Dio dio = Dio(BaseOptions(
      connectTimeout: defaultTimeout,
      receiveTimeout: defaultTimeout,
      sendTimeout: defaultTimeout));

  ApiClientBuilder addInterceptor(Interceptor interceptor) {
    dio.interceptors.add(interceptor);
    return this;
  }

  ApiClientBuilder ofUrl(String url) {
    dio.options.baseUrl = url;
    return this;
  }

  ApiClientBuilder setTimeout(int timeout) {
    dio.options.connectTimeout = timeout;
    dio.options.sendTimeout = timeout;
    dio.options.receiveTimeout = timeout;
    return this;
  }

  ApiClientBuilder setDefaultHeader() {
    dio.options.headers['Accept'] = 'application/json';
    return this;
  }

  Dio create() {
    (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
        (HttpClient client) {
      client.badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
      return client;
    };
    return dio;
  }
}


extension Builder on Dio {
  ApiClientBuilder newBuilder() {
    ApiClientBuilder builder = ApiClientBuilder();
    builder.dio = this;
    return builder;
  }
}

and use it just like this:

DioHelper.defaultApiClient.get('URL', queryParameters: queryParameters);
  • Related