我正在按照本教程创建连续创建的两个容器,单击这些容器时颜色会发生变化。
它使用了更长,更脏的代码版本。
enum GenderType { male, female }
class InputPage extends StatefulWidget {
@override
_InputPageState createState() => _InputPageState();
}
class _InputPageState extends State<InputPage> {
GenderType? selectedGender;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('BMI CALCULATOR'),
),
body: Column(
children: [
Expanded(
child: Row(
children: [
Expanded(
child: GestureDetector(
onTap: () {
setState(() {
selectedGender = GenderType.male;
});
},
child: ReusableContainer(
colour: selectedGender == GenderType.male
? activeCardColor
: inactiveContainerColor,
containerChild:
ContainerChildColumn(FontAwesomeIcons.male, "Male"),
),
),
),
Expanded(
child: GestureDetector(
onTap: () {
setState(() {
selectedGender = GenderType.female;
});
},
child: ReusableContainer(
colour: selectedGender == GenderType.female
? activeCardColor
: inactiveContainerColor,
containerChild: ContainerChildColumn(
FontAwesomeIcons.female, "Female"),
),
),
),
],
),
),
可重复使用的容器
import 'package:flutter/material.dart';
class ReusableContainer extends StatelessWidget {
ReusableContainer({@required this.colour, this.containerChild});
final Color? colour;
final Widget? containerChild;
@override
Widget build(BuildContext context) {
return Container(
child: containerChild,
margin: EdgeInsets.all(8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: colour,
),
);
}
}
但是,在本教程中,我们被要求“重构”并使代码更简洁。因此,我随后将GestureDetector窗口小部件转移到ReusableContainer类。
class ReusableContainer extends StatelessWidget {
ReusableContainer(
{@required this.colour, this.containerChild, this.ownOnTap});
final Color? colour;
final Widget? containerChild;
final Function? ownOnTap;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: ownOnTap?.call(),
child: Container(
child: containerChild,
margin: EdgeInsets.all(8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: colour,
和
Expanded(
child: Row(
children: [
Expanded(
child: ReusableContainer(
ownOnTap: () {
setState(() {
selectedGender = GenderType.male;
});
},
colour: selectedGender == GenderType.male
? activeCardColor
: inactiveContainerColor,
containerChild:
ContainerChildColumn(FontAwesomeIcons.male, "Male"),
),
),
Expanded(
child: ReusableContainer(
ownOnTap: () {
selectedGender = GenderType.female;
},
colour: selectedGender == GenderType.female
? activeCardColor
: inactiveContainerColor,
containerChild:
ContainerChildColumn(FontAwesomeIcons.female, "Female")
我逐行遵循了本教程,它应该可以正常工作。但是,它在我这边不起作用,而是显示此错误
我尝试删除两个小部件上的SetStates,但错误消失了,但是它没有用,因为按下时代码不会更新,颜色也不会改变。我该如何解决?
您正在通过直接调用该函数onTap: ownOnTap?.call(),
。相反,您必须尝试类似
GestureDetector(
onTap: () {
ownOnTap?.call();
}
// your code
)
或更简单
GestureDetector(
onTap: ownOnTap
// your code
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句