Flutter水平拾取器,设置状态不影响最大值

nwo49xxi  于 2023-05-19  发布在  Flutter
关注(0)|答案(1)|浏览(113)

我正在使用Flutter widget:HorizontalPicker
这里有一个非常简单的代码:

HorizontalPicker(
                  initialValue: Recipe.recipe.portionWeight.toInt(),
                  height: 70,
                  minValue: 0,
                  maxValue: Recipe.recipe.recipeWeight,
                  divisions: Recipe.recipe.recipeWeight.toInt(),
                  suffix: " g",
                  showCursor: false,
                  backgroundColor: Colors.grey.shade900,
                  activeItemTextColor: Colors.white,
                  passiveItemsTextColor: Colors.amber,
                  onChanged: (value) {
                    setState(() {
                      Recipe.recipe.portionWeight = value;
                      Recipe.calculatePortionGrams();
                      Speedometers.elaborateKcalNeedlePointer(value);
                      Recipe.updateRecipe();
                    });
                  },
                ),

不幸的是,这个小部件没有控制器。我的用户应该实时更改MAX值,但是一旦绘制到屏幕上,即使我以编程方式更改SetState上的MAX值,小部件也不会自行刷新。如果我改变页面或隐藏小部件本身,一旦返回值被刷新。
有解决方法吗?例如,如何将其隐藏一秒钟并再次显示?或者如何强制重绘小部件?

kognpnkq

kognpnkq1#

找到了解决方案:如何强制Flutter重建/重绘所有窗口小部件?
在包含HorizontalPicker的顶级小部件上使用了Key。要关注的用户是:肖恩布莱斯
这不是一个与我的问题直接相关的解决方案,这将解决任何其他小部件的任何其他问题。
这里的解决方案从那里复制:

  • 只需在您的高级小部件之一上使用Key,以下所有内容都将丢失状态:*
Key _refreshKey = UniqueKey();

void _handleLocalChanged() => setState((){ 
  _refreshKey = UniqueKey() 
});

Widget build(BuildContext context){
  return MaterialApp(
    key: _refreshKey ,
    ...

  )
}
  • 您也可以使用值键,如:*
return MaterialApp(
  key: ValueKey(locale.name)
  ...
);

相关问题