gpt4 book ai didi

flutter - 更新设置状态内的变量

转载 作者:IT王子 更新时间:2023-10-29 07:09:03 27 4
gpt4 key购买 nike

我是 Flutter 的新手,我有一个颜色列表,我希望能够触摸一个容器并在列表中的不同颜色之间切换。这将更新容器的颜色。此外,在本例 2 中我可以有多个容器,因此触摸一个容器不应更新其他容器。

我让它使用一个容器工作,但是在创建一个返回小部件的方法之后我可以有多个容器,这不起作用。

 import 'package:flutter/material.dart';

class NewGame extends StatefulWidget {
final Color team1;
final Color team2;
final Color team3;

NewGame(this.team1, this.team2, this.team3);

@override
_NewGameState createState() => _NewGameState();
}

class _NewGameState extends State<NewGame> {
List<Color> teamColors;
int team1Index = 0;
int team2Index = 0;

@override
void initState() {
super.initState();
teamColors = [widget.team1, widget.team2, widget.team3];
}

Widget _buildTeamSelector(int teamIndex) {
return GestureDetector(
onTap: () {
setState(() {
print('Value of teamColorIndex ${teamIndex.toString()}');
if (teamIndex < teamColors.length - 1) {
teamIndex++;
} else {
teamIndex = 0;
}
});
},
child: Container(
height: 75,
width: 75,
decoration: BoxDecoration(
color: teamColors[teamIndex],
borderRadius: BorderRadius.circular(50),
),
),
);
}

@override
Widget build(BuildContext context) {
return Card(
elevation: 5,
child: Column(
children: <Widget>[
Column(
children: <Widget>[
Text('Value of team1Index: :$team1Index'),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Teams:'),
_buildTeamSelector(team1Index),
_buildTeamSelector(team2Index),
Text('Red'),
],
),
],
),
],
),
);
}
}

I/flutter (12114): Value of teamColorIndex 0
I/chatty (12114): uid=10085(com.example.game_tracker) Thread-2 identical 1 line
I/flutter (12114): Value of teamColorIndex 0
I/flutter (12114): Value of teamColorIndex 0
I/chatty (12114): uid=10085(com.example.game_tracker) Thread-2 identical 4 lines
I/flutter (12114): Value of teamColorIndex 0
I/flutter (12114): Value of teamColorIndex 0

在 setState 中,变量似乎没有得到更新。我知道这是问题所在,但我不知道为什么。

最佳答案

您正在更新的变量不是您认为的那个。

你有两个同名的变量:

  • State 的属性
  • _buildTeamSelector 的参数

您在 setState 调用中更改的不是 State 属性,而是您方法的参数。

代替:

int a;
void foo(int a) {
a++;
}

做:

int a;
void foo(int a) {
this.a++; //properly update the instance member instead of the parameter
}

关于flutter - 更新设置状态内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57365721/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com