📅  最后修改于: 2023-12-03 14:51:34.412000             🧑  作者: Mango
在编写应用程序时,我们经常需要创建漂亮的用户界面。其中一种方式是使用星级小部件来提供反馈和评级功能。在本文中,我们将介绍如何在颤振中创建星级小部件。
以下是创建星级小部件的步骤:
flutter/material.dart
库和dart:ui
库。StatefulWidget
的新类,如RatingBar
。RatingBar
类中创建一个名为_rating
的私有变量,用于存储用户选择的等级。class RatingBar extends StatefulWidget {
@override
_RatingBarState createState() => _RatingBarState();
}
class _RatingBarState extends State<RatingBar> {
double _rating = 0.0;
}
_RatingBarState
类中创建一个名为_buildRatingBar
的私有方法,该方法将构建星级小部件。Widget _buildRatingBar() {
return Row(
children: [
Icon(Icons.star, size: 50.0),
Icon(Icons.star, size: 50.0),
Icon(Icons.star, size: 50.0),
Icon(Icons.star, size: 50.0),
Icon(Icons.star, size: 50.0),
],
);
}
_buildRatingBar
方法中,将所有五个星级图标放在一个Row
小部件中。_buildRatingBar
方法返回到build
方法中,其中build
方法必须返回一个小部件。class RatingBar extends StatefulWidget {
@override
_RatingBarState createState() => _RatingBarState();
}
class _RatingBarState extends State<RatingBar> {
double _rating = 0.0;
Widget _buildRatingBar() {
return Row(
children: [
Icon(Icons.star, size: 50.0),
Icon(Icons.star, size: 50.0),
Icon(Icons.star, size: 50.0),
Icon(Icons.star, size: 50.0),
Icon(Icons.star, size: 50.0),
],
);
}
@override
Widget build(BuildContext context) {
return Container(
child: _buildRatingBar(),
);
}
}
_RatingBarState
类中创建一个名为_updateRating
的私有方法,并在每个星型小部件上添加GestureDetector
小部件,可以为星级小部件添加用户输入。void _updateRating(int rating) {
setState(() {
_rating = rating.toDouble();
});
}
Widget _buildRatingBar() {
return Row(
children: [
GestureDetector(
onTap: () => _updateRating(1),
child: Icon(Icons.star, size: 50.0),
),
GestureDetector(
onTap: () => _updateRating(2),
child: Icon(Icons.star, size: 50.0),
),
GestureDetector(
onTap: () => _updateRating(3),
child: Icon(Icons.star, size: 50.0),
),
GestureDetector(
onTap: () => _updateRating(4),
child: Icon(Icons.star, size: 50.0),
),
GestureDetector(
onTap: () => _updateRating(5),
child: Icon(Icons.star, size: 50.0),
),
],
);
}
RatingBar
小部件在您的颤振应用程序中创建星级小部件。import 'package:flutter/material.dart';
import 'dart:ui';
class RatingBar extends StatefulWidget {
@override
_RatingBarState createState() => _RatingBarState();
}
class _RatingBarState extends State<RatingBar> {
double _rating = 0.0;
void _updateRating(int rating) {
setState(() {
_rating = rating.toDouble();
});
}
Widget _buildRatingBar() {
return Row(
children: [
GestureDetector(
onTap: () => _updateRating(1),
child: Icon(Icons.star, size: 50.0),
),
GestureDetector(
onTap: () => _updateRating(2),
child: Icon(Icons.star, size: 50.0),
),
GestureDetector(
onTap: () => _updateRating(3),
child: Icon(Icons.star, size: 50.0),
),
GestureDetector(
onTap: () => _updateRating(4),
child: Icon(Icons.star, size: 50.0),
),
GestureDetector(
onTap: () => _updateRating(5),
child: Icon(Icons.star, size: 50.0),
),
],
);
}
@override
Widget build(BuildContext context) {
return Container(
child: _buildRatingBar(),
);
}
}