以前,我曾经ListBuilder
生成一个包含 70 个数字的列表并且它可以工作,但是将 70 个数字生成到自定义小部件中需要很长时间,而且当我点击一个数字只是为了更改背景颜色状态时,之前需要几毫秒正在改变的状态。
现在我正在使用 aFutureBuilder
来加载屏幕,同时等待生成的 70 个整数。但是当我点击球号时,背景颜色没有更新......就像setState()
在 Future ListBuilder 中不起作用一样。
这个问题:“ Flutter - How to update state (or value?) of a Future/List used to build ListView (via FutureBuilder) ”非常相似,但它没有解决我的问题。
这是我在构建方法中的代码
Flexible(
child:FutureBuilder<List<Widget>>(
future: ballNumbers,
builder: (context, snapshot){
if(snapshot.connectionState != ConnectionState.done){
return Center(child: CircularProgressIndicator());
}
if(snapshot.hasError){
return Center(child: Text("An error has occured"));
}
List<Widget> balls = snapshot.data ?? [];
return GridView.count(
crossAxisCount: 9,
children: balls,
);
}
)
以下是我启动函数状态的方式:
Future<List<Widget>> ballNumbers;
List<int> picks = [];
@override
void initState() {
ballNumbers = getBallNumbers();
});
Future<List<Widget>> getBallNumbers() async {
return List.generate(limitBallNumber,(number){
number = number + 1;
return Padding(
padding:EdgeInsets.all(2.5),
child:Ball(
number : number,
size: ballWidth,
textColor:(picks.contains(number)) ? Colors.black : Colors.white,
ballColor: (picks.contains(number)) ? Style.selectedBallColor : Style.ballColor,
onTap:(){
setState((){
picks.contains(number) ? picks.remove(number) : picks.add(number);
});
}
)
);
});
}
更新:这是Ball
小部件的类
class Ball extends StatelessWidget {
final Color ballColor;
final Color textColor;
final double size;
final double fontSize;
final int number;
final VoidCallback onTap;
Ball({Key key, @required this.number,
this.textColor,
this.ballColor,
this.onTap,
this.size = 55.0,
this.fontSize = 14,
}) : super(key : key);
@override
Widget build(BuildContext context) {
return Container(
height: size,
width: size,
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: LinearGradient(
colors: [
Style.secondaryColor,
ballColor != null ? ballColor : Style.ballColor,
],
begin: Alignment.bottomLeft,
end: Alignment.topRight
)
),
child: FlatButton(
padding: EdgeInsets.all(0),
child: Container(
child: Text(
number.toString().length > 1 ? number.toString() : "0" + number.toString(),
style: TextStyle(
fontSize: fontSize,
color: textColor != null ? textColor : Colors.white
),
),
padding: const EdgeInsets.all(4.0),
decoration:BoxDecoration(
color: Colors.transparent,
border: Border.all(color: textColor != null ? textColor : Colors.white, width: 1),
borderRadius: BorderRadius.circular(32),
)
),
color: Colors.transparent,
onPressed: onTap,
),
);
}
}