温馨提示×

flutter怎么实现卡片切换效果

小亿
233
2024-01-11 16:44:23
栏目: 编程语言

在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回调函数,我们可以在切换卡片时更新底部导航栏的当前选中项。通过点击底部导航栏的选项,我们可以触发动画切换到对应的卡片。

0