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

flutter_fortune_wheel页面加载即自动转动,animateFirst无效的修复方案

解决flutter_fortune_wheel页面加载自动转动的问题

你遇到的问题根源在于selected参数使用了Stream.value(selected)——这个Stream会在组件初始化时立刻发射当前的selected值,哪怕设置了animateFirst: false,这个初始的Stream事件依然会触发转盘动画。

修复方案

改用可控的Stream(比如rxdart的BehaviorSubject),让Stream仅在点击按钮时发射值,具体步骤如下:

  1. 先在pubspec.yaml中添加rxdart依赖:
dependencies:
  rxdart: ^0.27.7 # 可替换为最新版本
  1. 修改页面代码,用BehaviorSubject控制Stream的发射时机:
import 'package:flutter/material.dart';
import 'package:flutter_fortune_wheel/flutter_fortune_wheel.dart';
import 'package:rxdart/rxdart.dart';
import 'dart:math';

class WheelPage extends StatefulWidget {
  const WheelPage({super.key});

  @override
  State<WheelPage> createState() => _WheelPageState();
}

class _WheelPageState extends State<WheelPage> {
  final _selectedSubject = BehaviorSubject<int>();
  final Random _random = Random();
  
  // 假设你已定义以下文本样式
  final TextStyle subtitleText = const TextStyle(fontSize: 18);
  final TextStyle smallText = const TextStyle(fontSize: 16, color: Colors.white);

  @override
  void dispose() {
    _selectedSubject.close(); // 组件销毁时关闭Subject,避免内存泄漏
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(
            child: FortuneWheel(
              selected: _selectedSubject.stream,
              animateFirst: false,
              duration: const Duration(seconds: 3),
              items: [
                FortuneItem(child: Text("1", style: subtitleText)),
                FortuneItem(child: Text("2", style: subtitleText)),
                FortuneItem(child: Text("3", style: subtitleText)),
                FortuneItem(child: Text("4", style: subtitleText)),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(20),
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                  fixedSize: const Size.fromHeight(40),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(50),
                  ),
                  backgroundColor: Colors.deepOrange,
                  elevation: 5,
                  shadowColor: Colors.black),
              onPressed: () {
                _selectedSubject.add(_random.nextInt(4)); // 点击时发射新值触发转动
              },
              child: Text(
                "spin",
                style: smallText,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

原理说明

  • BehaviorSubject初始不会发射任何值,因此页面加载时转盘保持静止
  • 只有点击按钮调用_selectedSubject.add(...)时,Stream才会发射新的选中索引,触发转盘动画
  • animateFirst: false确保后续的Stream事件不会触发额外的初始动画干扰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:35:32