评分
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePageWidget(),
);
}
}
class HomePageWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("例子"),
),
body: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
StarRating(rating: 4.5, size: 30,),
SizedBox(width: 10,),
Text("4.5分",style: TextStyle(fontSize: 20),),
],
),
),
);
}
}
class StarRating extends StatefulWidget {
final double rating;
final double maxRating;
final Widget unselectedImage;
final Widget selectedImage;
final int count;
final double size;
final Color unselectedColor;
final Color selectedColor;
StarRating({
@required this.rating,
this.maxRating = 10,
this.size = 20,
this.unselectedColor = const Color(0xffbbbbbb),
this.selectedColor = const Color(0xffe0aa46),
Widget unselectedImage,
Widget selectedImage,
this.count = 5,
}): unselectedImage = unselectedImage ?? Icon(Icons.star, size: size, color: unselectedColor,),
selectedImage = selectedImage ?? Icon(Icons.star, size: size, color: selectedColor);
@override
_StarRatingState createState() => _StarRatingState();
}
class _StarRatingState extends State<StarRating> {
@override
Widget build(BuildContext context) {
return Container(
child: Stack(
children: <Widget>[
Row(children: getUnSelectImage(), mainAxisSize: MainAxisSize.min,),
Row(children: getSelectImage(), mainAxisSize: MainAxisSize.min,),
],
),
);
}
// 获取评星
List<Widget> getUnSelectImage() {
return List.generate(widget.count, (index) => widget.unselectedImage);
}
List<Widget> getSelectImage() {
// 1.计算Star个数和剩余比例等
double oneValue = widget.maxRating / widget.count;
int entireCount = (widget.rating / oneValue).floor();
double leftValue = widget.rating - entireCount * oneValue;
double leftRatio = leftValue / oneValue;
// 2.获取start
List<Widget> selectedImages = [];
for (int i = 0; i < entireCount; i++) {
selectedImages.add(widget.selectedImage);
}
// 3.计算
Widget leftStar = ClipRect(
clipper: MyRectClipper(width: leftRatio * widget.size),
child: widget.selectedImage,
);
selectedImages.add(leftStar);
return selectedImages;
}
}
class MyRectClipper extends CustomClipper<Rect>{
final double width;
MyRectClipper({
this.width
});
@override
Rect getClip(Size size) {
return Rect.fromLTRB(0, 0, width, size.height);
}
@override
bool shouldReclip(MyRectClipper oldClipper) {
return width != oldClipper.width;
}
}
网友评论