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

Flutter Fortune Wheel组件无法获取选中值的求助

解决Flutter Fortune Wheel无法获取选中项的问题

我完全懂你遇到的困扰——转盘停转后拿不到选中的内容,之前你打印selected.stream只是输出了流对象本身,自然拿不到实际的选中值。咱们来一步步搞定这个问题:

问题根源

selected.stream是一个流对象,它本身并不是当前选中的索引值,你需要订阅这个流才能获取每次更新的数值。另外,你在onFling里手动add(1)是强制让转盘转到索引1的位置,如果想要随机旋转的效果,这显然不是最优的写法。

解决方案

我们可以在状态类里新增一个变量来保存当前选中的索引,通过订阅selected.stream来实时更新这个变量,这样在onAnimationEnd回调里就能直接用它获取选中项的内容了。

修改后的完整代码如下:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_fortune_wheel/flutter_fortune_wheel.dart';

class SpinawheelWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => SpinawheelState();
}

class SpinawheelState extends State<SpinawheelWidget> {
  StreamController<int> selected = StreamController<int>();
  int? _currentSelectedIndex; // 用于存储当前选中的索引

  @override
  void initState() {
    super.initState();
    // 订阅选中流,实时更新当前选中的索引
    selected.stream.listen((index) {
      setState(() {
        _currentSelectedIndex = index;
      });
    });
  }

  @override
  void dispose() {
    selected.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final items = <String>[
      'item1',
      'item2',
      'item3',
      'item4',
      'item5',
      'item6',
    ];
    return Column(
      children: [
        Expanded(
          child: FortuneWheel(
            physics: CircularPanPhysics(
              duration: Duration(seconds: 1),
              curve: Curves.decelerate,
            ),
            onFling: () {
              print('onFling');
              // 替换为随机生成索引,实现随机旋转效果
              selected.add(Fortune.randomInt(0, items.length));
            },
            onAnimationStart: () {
              print('animation start');
            },
            onAnimationEnd: () {
              if (_currentSelectedIndex != null) {
                final selectedItem = items[_currentSelectedIndex!];
                print('animation end,选中项:$selectedItem,索引:$_currentSelectedIndex');
              }
            },
            animateFirst: false,
            selected: selected.stream,
            items: [
              for (var it in items) FortuneItem(child: Text(it)),
            ],
          ),
        ),
      ],
    );
  }
}

关键改动说明

  1. 新增_currentSelectedIndex变量,专门用来存储每次流更新的选中索引
  2. 在initState中订阅selected.stream,确保每次流有新值时都能同步更新这个变量
  3. 在onAnimationEnd里,通过_currentSelectedIndex直接从items数组中获取对应的选中内容,就能正常输出结果了
  4. 额外优化:把onFling里的固定索引替换成Fortune.randomInt(0, items.length),实现真正的随机转盘效果

这样修改后,你就能在转盘停转后准确拿到选中的内容和对应的索引啦!

内容的提问来源于stack exchange,提问作者Mr. Tacio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 19:47:41