我正在学习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; }); }, ) ], ), ); } }
问题: 在上面的示例中,margin不是 状态变量 。它是build方法内部的局部变量。
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 } }