我正在尝试按照以下说明在继承的小部件/状态中调用设置状态 https://medium.com/flutter-community/widget-state-buildcontext-inheritedwidget-898d671b7956
在我不熟练的专家看来,他在做同样的事情,但显然我错过了一些。你能帮我吗?
class InhCore extends InheritedWidget {
InhCore({Key key, @required Widget child, @required this.data})
: super(key: key, child: child);
final InhState data;
@override
bool updateShouldNotify(InhCore oldWidget) {
return true;
}
}
class InhWidget extends StatefulWidget {
InhWidget({this.child});
final Widget child;
@override
State<StatefulWidget> createState() => InhState();
static InhState of(BuildContext context) {
return (context.inheritFromWidgetOfExactType(InhCore) as InhCore).data;
}
}
class InhState extends State<InhWidget> {
final Map<String, int> cardMap = {
'A':1,
'2':2,
'3':3,
'4':4,
'5':5,
'6':6,
'7':7,
'8':8,
'9':9,
'10':0,
'J':0,
'Q':0,
'K':0
};
List<String> cardDisplayed;
void deal(String card) => setState(() => cardDisplayed.add(card));
@override
Widget build(BuildContext context) {
return new InhCore(
data: this,
child: widget.child,
);
}
}
class CardButton extends StatelessWidget {
final String input;
CardButton({this.input});
Widget build(BuildContext context) {
final InhState state = InhWidget.of(context);
return Container(
width: 55.0,
height: 55.0,
child: Material(
color: Colors.grey[200],
child: InkWell(
onTap: state.deal(input),
child: Center (
child:Text(input),
),
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的帮助
你错过了 () =>
onPressed: () => state.deal(input)
Run Code Online (Sandbox Code Playgroud)
您的代码将调用的结果传递state.deal(input)给onPressed,而上面的代码传递了一个函数,该函数在被调用时调用state.deal(input)
| 归档时间: |
|
| 查看次数: |
976 次 |
| 最近记录: |