You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter开发:页面返回后如何保留Carousel的选中位置?

解决方案

要让Carousel在返回页面时保留上次选中的位置,核心是保存当前选中的页码,并在页面重建时用这个页码作为初始页。具体实现如下:

关键修改点

  • 新增变量记录当前选中的页码
  • 给CarouselOptions添加回调实时更新页码
  • 将初始页设置为保存的页码而非固定值0

修改后的完整代码

import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';

class TestPage extends StatefulWidget {
  const TestPage({Key? key}) : super(key: key);

  @override
  State<TestPage> createState() => _TestPage();
}

class _TestPage extends State<TestPage> {
  // 记录当前选中的页码,初始为0
  int _currentPage = 0;

  @override
  initState() {
    super.initState();
  }

  final double weatherIconWidth = 80;
  final double weatherIconHeight = 90;
  final double weatherFontSize = 12;

  final weatherImages = [
    'assets/images/weather/sun.png',
    'assets/images/weather/sun_cloud.png',
    'assets/images/weather/cloud.png',
    'assets/images/weather/light_rain.png',
    'assets/images/weather/heavey_rain.png',
    'assets/images/weather/storm.png',
    'assets/images/weather/snow.png',
  ];
  var weatherList = [
    'Sunny',
    'Sun & Cloud',
    'Cloudy',
    'Showers',
    'Rain',
    'Storms',
    'Ice & Snow'
  ];

  Widget buildWeatherImage(String weatherImage, int index) => Container(
        margin: const EdgeInsets.symmetric(horizontal: 5),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Image.asset(weatherImage, fit: BoxFit.cover),
            Text(
              weatherList[index],
              style: TextStyle(
                  fontSize: weatherFontSize, fontWeight: FontWeight.bold),
            ),
          ],
        ),
      );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: (const Text('Carousel')),
        automaticallyImplyLeading: false,
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.chevron_left),
            onPressed: () {
              Navigator.pop(context);
            },
          )
        ],
      ),
      body: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          Container(
            padding: const EdgeInsets.only(left: 10),
            child: Column(
              children: [
                const Text(
                  'Weather',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(
                  width: weatherIconWidth,
                  child: CarouselSlider.builder(
                    options: CarouselOptions(
                      height: weatherIconHeight,
                      // 使用保存的页码作为初始页
                      initialPage: _currentPage,
                      viewportFraction: 1,
                      // 页码变化时更新记录值
                      onPageChanged: (index, reason) {
                        setState(() {
                          _currentPage = index;
                        });
                      }
                    ),
                    itemCount: weatherImages.length,
                    itemBuilder: (context, index, realIndex) {
                      final weatherImage = weatherImages[index];
                      return buildWeatherImage(weatherImage, index);
                    },
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

补充说明

  • 当通过Navigator.push跳转到其他页面再返回时,TestPage的State对象会被保留,_currentPage会维持最后选中的页码,Carousel就能从该位置展示。
  • 如果需要APP重启后仍能记住选中位置,可以搭配shared_preferences库,在onPageChanged时将页码写入本地存储,在initState时读取并赋值给_currentPage。

内容的提问来源于stack exchange,提问作者Sean

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 14:07:50