flutter CustomScrollView自定义滚动抖动

eqqqjvef  于 2022-12-30  发布在  Flutter
关注(0)|答案(1)|浏览(195)

我一直在研究和尝试做一些项目和堆栈在这方面。所以,我创建了自定义滚动视图和sliverappbar必须要么完全打开或完全关闭。我尝试这样做,但有问题的动画滚动。

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.deepPurple,
        ),
        body: const MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {
  final _scrollController = ScrollController();
  bool isClosed = false;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.offset >= 5 && _scrollController.offset <= 200) {
        if (isClosed) {
          _scrollController.jumpTo(0);
          close();
        } else {
          _scrollController.jumpTo(202);
          close();
        }
      }
    });
  }

  close() {
    setState(() {
      isClosed = !isClosed;
    });
  }

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      controller: _scrollController,
      slivers: [
        SliverAppBar(
          expandedHeight: 200,
          flexibleSpace: SizedBox(
            child: Container(
              height: 200,
              decoration: const BoxDecoration(
                  image: DecorationImage(
                      image: NetworkImage(
                          "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS5-OgasVpm-kc2HaOUloxKVlLzLuM6Q53mfA&usqp=CAU"),
                      fit: BoxFit.cover)),
            ),
          ),
        ),
        SliverList(
            delegate: SliverChildBuilderDelegate(
          (BuildContext context, int index) {
            return Container(
              color: Color(index),
              height: 100,
              width: MediaQuery.of(context).size.width,
              child: Text("$index"),
            );
          },
          childCount: 10,
        ))
      ],
    );
  }
}

使用jumpTo时可以正常工作,但使用animateTo时会出现问题。谢谢!

k2fxgqgv

k2fxgqgv1#

您需要将.animateTo() Package 在Future delay中。

Future.delayed(
  Duration(milliseconds: 600),
  () {
    _scrollController.animateTo(
    202,
    duration: Duration(
        milliseconds: 600),
    curve: Curves.ease);
});

或者,您也可以在PostFrameCallback中进行 Package

WidgetsBinding.instance.addPostFrameCallback((_) {
    _scrollController.animateTo(
    202,
    duration: Duration(
        milliseconds: 600),
    curve: Curves.ease);
}

相关问题