Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CustomScrollView如何定位到类似于SliverToBoxAdapter之类的其他Sliver组件。 #82

Open
JDongKhan opened this issue May 22, 2024 · 2 comments
Assignees

Comments

@JDongKhan
Copy link

JDongKhan commented May 22, 2024

您好,有些场景不知道如何使用,能帮忙看一下吗? 谢谢。

Platforms

Android, iOS

Description

从demo上都在在解决CustomScrollView里面SliverList和SliverGrid的问题,没有看到有关其他sliver组件的解决方案。

My code

import 'package:flutter/material.dart';
import 'package:scrollview_observer/scrollview_observer.dart';

import 'custom_scrollview_demo_page.dart';

void main() {
  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final ScrollController _scrollController = ScrollController();
  late SliverObserverController observerController;

  void _incrementCounter() {
    // 动画滚动至下标位置
    observerController.animateTo(
      index: 8,
      duration: const Duration(seconds: 1),
      curve: Curves.ease,
    );
  }

  @override
  void initState() {
    observerController = SliverObserverController(controller: _scrollController);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: SliverViewObserver(
        controller: observerController,
        child: CustomScrollView(
          controller: _scrollController,
          slivers: List.generate(
            10,
            (index) => SliverToBoxAdapter(
              child: GestureDetector(
                onTap: () {
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (_) => CustomScrollViewDemoPage(),
                    ),
                  );
                },
                child: Container(
                  color: Colors.grey,
                  margin: const EdgeInsets.all(12),
                  child: Text(index.toString()),
                  height: 100,
                ),
              ),
            ),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Try do it

这样搞没有效果,还需要额外实现其他方法吗?

@LinXunFeng
Copy link
Member

scrollview_observer 没有提供滚动到指定 sliver 位置的功能,不过你可以通过如下代码实现

  final ScrollController _scrollController = ScrollController();
  late SliverObserverController observerController;

  Map<int, BuildContext> _sliverContextMap = {};

  void _incrementCounter() {
    final renderObj = ObserverUtils.findRenderObject(_sliverContextMap[8]);
    if (renderObj is! RenderSliver) return;
    // 动画滚动至下标位置
    _scrollController.animateTo(
      renderObj.constraints.precedingScrollExtent,
      duration: const Duration(seconds: 1),
      curve: Curves.ease,
    );
  }

...

        child: CustomScrollView(
          controller: _scrollController,
          slivers: List.generate(
            10,
            (index) {
              Widget resultWidget = SliverToBoxAdapter(
                child: GestureDetector(
                  onTap: () {
                    Navigator.of(context).push(
                      MaterialPageRoute(
                        builder: (_) => CustomScrollViewDemoPage(),
                      ),
                    );
                  },
                  child: Container(
                    color: Colors.grey,
                    margin: const EdgeInsets.all(12),
                    child: Text(index.toString()),
                    height: 100,
                  ),
                ),
              );
              resultWidget = SliverObserveContext(
                onObserve: (ctx) {
                  _sliverContextMap[index] = ctx;
                },
                child: resultWidget,
              );
              return resultWidget;
            },
          ),
        ),

@JDongKhan
Copy link
Author

多谢,我试试。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants