Warm tip: This article is reproduced from stackoverflow.com, please click
flutter

Flutter Slider Not Moving or Updating

发布于 2020-03-27 15:46:50

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;
              });
            },
          )
        ],
      ),
    );
  }
}
Questioner
themene
Viewed
440
Dinesh Balasubramanian 2018-08-25 00:30

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

Fix: Move this as an instance variable.

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

Code:

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