[list=1]flutter初始化列表的时候,不给默认值报错,求flutter大佬救救萌新!!
[/list]
import 'package:flutter/material.dart';
main() {
runApp(const MyDemo());
}
class MyDemo extends StatelessWidget {
const MyDemo({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(home: (
Scaffold(
appBar: AppBar(
title:const Text('异步操作')
),
// body: SafeArea(child: HomeBody()),
body: const HomeBody(),
)
));
}
}
class HomeBody extends StatefulWidget {
const HomeBody({super.key});
@override
State<HomeBody> createState() => _HomeBodyState();
}
class _HomeBodyState extends State<HomeBody> {
@override
void initState() {
// TODO: implement initState
super.initState();
}
@override
Widget build(BuildContext context) {
return StarRate(score: 9,activeImage: const Icon(Icons.heart_broken));
}
}
class StarRate extends StatefulWidget {
final double score;
final double maxScore;
final int starCount;
final double starSize;
final Color activeColor;
final Color defaultColor;
final Widget defaultImage;
final Widget activeImage;
StarRate({
required this.score,
this.maxScore = 10,
this.starCount = 6,
this.starSize = 32,
this.activeColor = Colors.red,
this.defaultColor = const Color.fromRGBO(0, 0, 0, 0.3),
Widget defaultImage,
Widget activeImage
}) :defaultImage = defaultImage ?? Icon(Icons.star_border,color:defaultColor,size: starSize),
activeImage = activeImage ?? Icon(Icons.star,color: activeColor,size: starSize);
@override
State<StarRate> createState() => _StarRateState();
}
class _StarRateState extends State<StarRate> {
@override
Widget build(BuildContext context) {
return Stack(
children: [
Row(
children: List.generate(widget.starCount, (index){
return widget.defaultImage;
})
),
Row(
children: buildSelectedStar())
],
);
}
List<Widget>buildSelectedStar(){
// 1.创建stars
List<Widget> stars = [];
// 2.构建填充的star
double oneValue = widget.maxScore / widget.starCount;
int entireStar = (widget.score / oneValue).floor();
final star = widget.activeImage;
for(var i = 0; i<entireStar;i++){
stars.add(star);
}
// 3.填充部分star
double leftWidth = ((widget.score/oneValue) - entireStar) * widget.starSize;
final sectionStar = ClipRect(
clipper: StarClip(leftWidth),
child: star
);
stars.add(sectionStar);
return stars;
}
}
class StarClip extends CustomClipper<Rect>{
double width;
StarClip(this.width);
@override
Rect getClip(Size size) {
return Rect.fromLTRB(0, 0, width, size.height);
}
@override
bool shouldReclip(StarClip oldClipper) {
return oldClipper.width != width;
}
}
|