问题1:在拦截器的代码中,我希望判断code值,直接用toast提示错误信息,但是,我看toast的使用需要用到BuildContext,那么在非组件的代码中,我要怎么才能拿到content?
class CustomInterceptors extends Interceptor {
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
print('REQUEST[${options.method}] => PATH: ${options.path}');
return super.onRequest(options, handler);
}
@override
void onResponse(Response response, ResponseInterceptorHandler handler) {
print('RESPONSE[${response.statusCode}] => PATH: ${response.requestOptions.path}');
//此处写toast提示逻辑
return super.onResponse(response, handler);
}
@override
void onError(DioError err, ErrorInterceptorHandler handler) {
print('ERROR[${err.response?.statusCode}] => PATH: ${err.requestOptions.path}');
return super.onError(err, handler);
}
}
toast使用代码
final snackBar = SnackBar(content: Text('Yay! A SnackBar!'));
// 从组件树种找到ScaffoldMessager,并用它去show一个snackBar
ScaffoldMessenger.of(context).showSnackBar(snackBar);
此处使用拦截器
class Request {
static Dio dio = Dio(BaseOptions(
baseUrl: MConfig.BASE_URL,
connectTimeout: 30 * 1000,
// receiveTimeout: 3000,
))
..interceptors.add(CustomInterceptors());
...
}
问题2:import as引入get包,使用它的函数时报错
Try importing the library that defines 'offAllNamed', correcting the name to the name of an existing function, or defining a function named 'offAllNamed'
import 'package:get/get.dart' as route;
...
if ([20005].contains(code)){
// BrnToast.show("共找到10932个结果", context, duration: BrnToast.LENGTH_LONG);
route.offAllNamed("/login");
return throw Exception(res.data["msg"]);
}
...
你是从哪里叫
CustomInterceptors
? 可以试看将context
带进来关于你第二个报错,用
route.Get.offAllNamed("/login");