温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Flutter Slider Not Moving or Updating

其他 - 颤振滑块不移动或更新

发布于 2020-03-27 16:17:18

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

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;
              });
            },
          )
        ],
      ),
    );
  }
}

查看更多

查看更多

提问者
themene
被浏览
73
Dinesh Balasubramanian 2018-08-25 00:30

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

修复:将其移动为实例变量。

原因:窗口小部件只有在状态发生变化时才可以重建

码:

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
  }
}

发布
问题

分享
好友

手机
浏览

扫码手机浏览