Rock Book

history | grep `future`

Flutter でScrollView がrebuild されたときにscroll to top したい

TL;DR

scheduler 使うとよい。(マサカリ歓迎)

import 'package:flutter/scheduler.dart';

class _MyWidgetState extends State<MyWidget> {
  ScrollController _controller;

  @override
  void initState() {
    super.initState();
    _controller = ScrollController();
  }

  @override
  Widget build(BuildContext context) {
    if (_controller.hasClients) {
      SchedulerBinding.instance.addPostFrameCallback((_) =>
          _controller.jumpTo(0.0));
    }

    return Container(
      child: ...

エラーログ

そのままやると:

  Widget build(BuildContext context) {
    if (_controller.hasClients) {
      _controller.jumpTo(0.0);
    }

怒られる

Performing hot reload...
Syncing files to device iPhone XR...
Reloaded 1 of 553 libraries in 949ms.
flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building MyWidget(dirty, dependencies:
flutter: [_LocalizationsScope-[GlobalKey#ab210], _InheritedTheme], state: _MyWidgetState#100b7):
flutter: Unexpected call to replaceSemanticsActions() method of RawGestureDetectorState.
flutter: The replaceSemanticsActions() method can only be called outside of the build phase.

参考

  • medium.com

    • 今回はjumpTo を使ったけどanimateTo などもある
  • flutterbyexample.com

    • (re) build の後に必ず呼ばれるメソッドが見つけられなかった。というかどこかにオフィシャルドキュメントありそう
  • stackoverflow.com

    • 自分はエラーメッセージから類推して「flutter how to add task after build phase has finished」でググって行き着いた

さて、なにしようとしてたんだっけ。そうだ、朝メシ。