问题描述
Flutter中使用showDialog
或showModalBottomSheet
后,通过setState()
无法更新当前dialog。其实原因很简单,因为dialog其实是另一个页面,准确地来说是另一个路由,因为dialog的关闭也是通过navigator.pop
的,所以地位与当前主页面一样。这个概念一定要明确,因为无论在Android或iOS中,daliog都是依附于当前主页面的一个控件,但是在Flutter中不同,它是一个新的路由。所以使用当前主页面的setState()
来更新,当然没法达到所要的效果。
showDialog
方法的API注释中也明确说明了这一点,dialog所持有的context已经变了:
This widget does not share a context with the location that showDialog is originally called from. Use a [StatefulBuilder] or a custom [StatefulWidget] if the dialog needs to update dynamically.
所以我们有两种方法来解决这个问题,一种是使用StatefulBuilder&