flutter提供者与“上下文上下文"和“上下文"有什么区别 [英] flutter provider what is the difference with 'Context context' and 'context '
问题描述
```
import 'package:a_class_flutter/provider/ac_score/ac_score_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
class ACScoreView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => ACScoreProvider(),
builder: (context, child) {
return Stack(
children: <Widget>[
_topMenu(context),
],
);
},
);
}
}
// Important!
Widget _topMenu(BuildContext context) {
return GestureDetector(
onTap: () {
context.read<ACScoreProvider>().showTopMenueStatus();
},
child: Container(
width: double.infinity,
height: double.infinity,
color: Colors.red,
child: Stack(
children: <Widget>[
Positioned(
child: AnimatedOpacity(
duration: Duration(microseconds: 100),
opacity:
context.watch<ACScoreProvider>().needShowTopMenue ? 1.0 : 0.0,
child: Container(
width: double.infinity,
height: ScreenUtil().setHeight(60),
color: Colors.black,
),
),
)
],
),
),
);
}
```
这是我的代码,可以正常工作,但是当我尝试将 Widget _topMenu(BuildContext context)
更改为 Widget _topMenu(context)
时,Flutter给了我一个错误这是:
This is my code which is working well, but when I try to change Widget _topMenu(BuildContext context)
to Widget _topMenu(context)
, Flutter gives me an error which is:
The following NoSuchMethodError was thrown building Builder(dirty, dependencies: [_InheritedProviderScope<ACScoreProvider>]): Class 'StatelessElement' has no instance method 'watch'. Receiver: Instance of 'StatelessElement'. Tried calling: watch<ACScoreProvider>().The relevant error-causing widget was ChangeNotifierProvider<ACScoreProvider> package:a_class_flutter/…/ac_score/ac_score.dart:9.
为什么缺少 BuildContext
声明可能导致此错误?我需要将每个上下文都放到BuildContext吗?
Why missing BuildContext
declaration could cause this error? Do I need to put every context with BuildContext?
推荐答案
来自提供商文档:
读取值的最简单方法是使用[BuildContext]上的扩展方法:
The easiest way to read a value is by using the extension methods on [BuildContext]:
-
context.read< T>()
,它会返回T,而不会监听
context.read<T>()
, which returns T without listening to it
仅编写 Widget _topMenu(context)
,将 context
参数推断为动态上下文
,而不是 BuildContext上下文
,因此您没有要调用的扩展方法 .read< T>()
.
Writing just Widget _topMenu(context)
, the context
parameter is inferred as a dynamic context
not BuildContext context
and hence you it does not have the extension method .read<T>()
you are trying to call.
如果它在 StatefulWidget
内部,则不会有问题,因为它的 State
类具有实例
If it were inside a StatefulWidget
, this wouldn't have been a problem because it's State
class has a instance context
(type BuildContext
) property and so the extension method .read<T>()
can be called on it.
这篇关于flutter提供者与“上下文上下文"和“上下文"有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!