颤振滑块不移动或更新 [英] Flutter Slider Not Moving or Updating

查看:323
本文介绍了颤振滑块不移动或更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Flutter(以及一般的编码方法),而我的最新项目似乎找不到问题.当我在模拟器中运行时,滑块的形状就很好,单击拇指并显示标签,但是拇指根本不会在轨道上移动,因此永远不会调用onChanged事件.

I'm learning Flutter (and coding in general) and I can't seem to find the issue with my latest project. When I run in simulator the slider forms just fine, click the thumb and the label shows, but the thumb won't move on the track at all, and thus never calls the onChanged event.

import 'resources.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';

class ItemDetail extends StatefulWidget {
  final Item item;

  ItemDetail({Key key, @required this.item}) : super(key: key);

  @override
  _ItemDetailState createState() => new _ItemDetailState(item: item);
}

class _ItemDetailState extends State<ItemDetail> {
  Item item;

  _ItemDetailState({Key key, @required this.item});

  @override
  Widget build(BuildContext context) {
    double margin = ((item.listPrice - item.stdUnitCost)/item.listPrice)*100;
    return new Scaffold(
      appBar: AppBar(
        title: new Text('Item Detail'),
      ),
      body: new Column(
        children: <Widget>[
          new Padding(padding: EdgeInsets.symmetric(vertical: 20.0)),
          new Text(item.itemCode),
          new Text(item.itemDescription),
          new Text(item.itemExtendedDescription),
          new Divider(height: 40.0,),
          new Text('List Price: \$${item.listPrice}'),
          new Text('Cost: \$${item.stdUnitCost}'),
          item.itemType=='N'
              ? new Text('Non-Stock (${item.itemType})')
              : new Text('Stock Item (${item.itemType})'),
          new Text('Available: ${item.stockAvailable}'),
          new Padding(padding: EdgeInsets.symmetric(vertical: 10.0)),
          new Slider(
            value: margin,
            divisions: 20,
            min: 0.0,
            max: 100.0,
            label: margin.round().toString(),
            onChanged: (double value) {
              setState(() {
                margin = value;
              });
            },
          )
        ],
      ),
    );
  }
}

推荐答案

问题:在上例中,margin不是状态变量.它是build方法内部的局部变量.

Problem: In the above example, margin is not a state variable. It is a local variable inside a build method.

修复:将其作为 instance 变量移动.

Fix: Move this as an instance variable.

原因:仅当其状态更改时,窗口小部件才会得到重建.

Reason: Widgets will get rebuild only when there is a change in its state.

代码:

class _ItemDetailState extends State<ItemDetail> {
  Item item;
  var margin;

  _ItemDetailState({Key key, @required this.item}) {
    this.margin = ((item.listPrice - item.stdUnitCost)/item.listPrice)*100;
  }

  @override
  Widget build(BuildContext context) {
    //same as now
  }
}

这篇关于颤振滑块不移动或更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆