在Flutter中實現卡片切換效果可以通過使用PageView組件來實現。以下是一個簡單的示例代碼:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: CardSwitcher(),
);
}
}
class CardSwitcher extends StatefulWidget {
@override
_CardSwitcherState createState() => _CardSwitcherState();
}
class _CardSwitcherState extends State<CardSwitcher> {
PageController _pageController;
int _currentIndex = 0;
@override
void initState() {
_pageController = PageController(initialPage: _currentIndex);
super.initState();
}
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Card Switcher'),
),
body: PageView(
controller: _pageController,
onPageChanged: (int index) {
setState(() {
_currentIndex = index;
});
},
children: [
Card(
color: Colors.red,
child: Center(
child: Text('Card 1',
style: TextStyle(fontSize: 24, color: Colors.white)),
),
),
Card(
color: Colors.blue,
child: Center(
child: Text('Card 2',
style: TextStyle(fontSize: 24, color: Colors.white)),
),
),
Card(
color: Colors.green,
child: Center(
child: Text('Card 3',
style: TextStyle(fontSize: 24, color: Colors.white)),
),
),
],
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (int index) {
setState(() {
_currentIndex = index;
_pageController.animateToPage(
_currentIndex,
duration: Duration(milliseconds: 500),
curve: Curves.ease,
);
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Card 1',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Card 2',
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'Card 3',
),
],
),
);
}
}
在上面的示例代碼中,我們使用PageView組件來展示卡片,并通過PageController來控制卡片的切換。通過設置onPageChanged回調函數,我們可以在切換卡片時更新底部導航欄的當前選中項。通過點擊底部導航欄的選項,我們可以觸發動畫切換到對應的卡片。