如何在 Flutter 中使用函数可靠地找到并滚动可滚动的 widget?

问题描述 投票:0回答:1

这是我正在使用的小部件:

import 'package:flutter/material.dart';

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    const settings = Center(
      child: Text(
        'Home 1',
        style: TextStyle(
          color: Colors.white
        ),
      ),
    );
    const settings2 = Center(
      child: Text(
        'Home 2',
        style: TextStyle(
          color: Colors.white
        ),
      ),
    );
    const children = <Widget>[
      ListTile(
        title: settings
      ),
      ListTile(
        title: settings2
      ),
      ListTile(
        title: settings
      ),
      ListTile(
        title: settings2
      ),
      ListTile(
        title: settings
      ),
      ListTile(
        title: settings2
      ),
      ListTile(
        title: settings
      ),
      ListTile(
        title: settings2
      ),
      ListTile(
        title: settings
      ),
      ListTile(
        title: settings2
      ),
      ListTile(
        title: settings
      ),
      ListTile(
        title: settings2
      ),
      ListTile(
        title: settings
      ),
      ListTile(
        title: settings2
      ),
      ListTile(
        title: settings
      ),
      ListTile(
        title: settings2
      ),
      ListTile(
        title: settings
      ),
      ListTile(
        title: settings2
      ),
      ListTile(
        title: settings
      ),
      ListTile(
        title: settings2
      ),
      ListTile(
        title: settings
      ),
      ListTile(
        title: settings2
      ),
      ListTile(
        title: settings
      ),
      ListTile(
        title: settings2
      ),
    ];

    return Center(
      child: SingleChildScrollView(
        key: GlobalKey(debugLabel: 'home'),
        controller: ScrollController(),
        child: const Column(children: children),
      ),
    );
  }
}

这是我获取可滚动状态的方法:

final dynamic renderObject = key.currentContext!.findRenderObject();
final dynamic scrollableContext = key.currentContext;
final ScrollableState scrollableState = Scrollable.of(scrollableContext);

这是我收到的错误消息:

No Scrollable widget ancestor could be found starting from the context that was passed to Scrollable.of(). This can happen because you are using a widget that looks for a Scrollable ancestor, but no such ancestor exists.

可以确认上下文已附加到 SingleChildView,但它仍然表示没有可滚动的祖先。我想知道发生了什么。

flutter scrollable
1个回答
0
投票

ScrollablePositionedList 如果您想在 ListView 中找到某个项目并滚动到它(https://pub.dev/packages/scrollable_positioned_list),我更喜欢它。 您可以使用 ItemScrollController 通过索引(项目位置)轻松地 scrollTojumpTo

itemScrollController.scrollTo({
  required int index,
  required Duration duration,
  double alignment = 0,
});
© www.soinside.com 2019 - 2024. All rights reserved.