如何使一个简单的轮播只使用PageView扑动?因为我需要知道如何使用PageController制作一个carousel。animeToPage颤振,这是可用的文档https://docs.flutter.dev/cookbook/animation/page-route-animation
import 'dart:async';
import 'package:flutter/material.dart';
class SignInPage extends StatefulWidget {
static const routeName = "/sign-in";
const SignInPage({Key? key}) : super(key: key);
@override
State<SignInPage> createState() => _SignInPageState();
}
class _SignInPageState extends State<SignInPage> {
int _selectedPage = 0;
late final _pageController = PageController(initialPage: _selectedPage);
late final Timer? _timer;
List<int> get _pageItem => [0, 1, 2, 3];
@override
void initState() {
super.initState();
_timer = Timer.periodic(Duration(seconds: 3), (time) async {
final nexPage = (_pageController.page?.toInt() ?? 0) + 1;
await _pageController.animateToPage(
nexPage,
duration: Duration(seconds: 1),
curve: Curves.easeOut,
);
});
}
@override
void dispose() {
super.dispose();
_pageController.dispose();
_timer?.cancel();
}
void _pageChanged(int currentPage) {
print("current page $currentPage");
_selectedPage = currentPage % _pageItem.length;
print("selected page $_selectedPage");
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: PageView.builder(
controller: _pageController,
onPageChanged: _pageChanged,
itemBuilder: (context, index) {
return Center(
child: Text(_pageItem[_selectedPage].toString()),
);
},
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
...List.generate(
_pageItem.length,
(index) => Icon(
Icons.circle,
color: index == _selectedPage ? Colors.blue : Colors.white,
),
),
],
),
Padding(
padding: const EdgeInsets.all(16),
child: ElevatedButton(
child: Text(
"Button",
),
onPressed: () async {
},
),
),
],
),
),
);
}
}
在这段代码中,您只使用PageView, PageController和Timer Periodic来使其旋转