昨天從其他頁(yè)面回到首頁(yè)霹琼,滑動(dòng)banner圖切換時(shí)發(fā)現(xiàn)一個(gè)錯(cuò)誤点额,雖然沒(méi)有導(dǎo)致崩潰咪啡,但是總是覺(jué)得不舒服:
Unhandled Exception: 'package:flutter/src/widgets/scroll_controller.dart':
Failed assertion: line 110 pos 12: '_positions.isNotEmpty': ScrollController not attached to any scroll views.
#0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39)
#1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5)
#2 ScrollController.position
由于bannerView是通過(guò)pageView組件來(lái)實(shí)現(xiàn)的坷随,在觸發(fā)PageController的animateToPage方法發(fā)生的這個(gè)錯(cuò)誤房铭,我嘗試著將animateToPage方法替換成jumpTo方法,還是回出現(xiàn)這個(gè)錯(cuò)誤温眉,說(shuō)明這應(yīng)該是PageController對(duì)象出現(xiàn)錯(cuò)誤導(dǎo)致的缸匪,繼續(xù)查看源碼發(fā)現(xiàn),PageController是繼承自ScrollController控制器的类溢,然后我在scroll_controller文件全局搜索 '_positions.isNotEmpty'找到來(lái)這個(gè)錯(cuò)誤的根源凌蔬,
Future<void> animateTo(
double offset, {
@required Duration duration,
@required Curve curve,
}) {
assert(_positions.isNotEmpty, 'ScrollController not attached to any scroll views.');
final List<Future<void>> animations = List<Future<void>>(_positions.length);
for (int i = 0; i < _positions.length; i += 1)
animations[i] = _positions[i].animateTo(offset, duration: duration, curve: curve);
return Future.wait<void>(animations).then<void>((List<void> _) => null);
}
通過(guò)源碼發(fā)現(xiàn),animateTo方法中有一個(gè)斷言闯冷,如果_positions.isNotEmpty砂心,就回拋出這個(gè)錯(cuò)誤,繼續(xù)搜索_positions.isNotEmpty發(fā)現(xiàn)指向來(lái)一個(gè)變量hasClients蛇耀,很明顯只要在執(zhí)行animateTo方法前判斷一下hsaClients方法就可以了辩诞,
if(_pageController.hasClients) {
_pageController.animateToPage(
_curIndex,
duration: Duration(milliseconds: 300),
curve: Curves.linear,
);
}
只需要在_pageController.hasClients為true的情況下,也就是說(shuō)_pageController已經(jīng)依附于pageView的情況下蒂窒,才能夠調(diào)用animateToPage方法躁倒,這里要注意的是,除了animateToPage方法洒琢,當(dāng)調(diào)用position,position褐桌,jumpTo等方法都回存在這個(gè)問(wèn)題衰抑,特別是第二次中心構(gòu)建頁(yè)面的時(shí)候需要注意。