使用jumpto和sticky_headers包会导致UI问题

时间:2019-09-16 13:07:32

标签: flutter dart

我创建了一个新的flutter项目,并添加了sticky_headers程序包。

然后,我实现了一个具有ScrollController的列表生成器。 我每隔5秒调用一次setState 3次,并修改一个全局偏移量变量,该变量将在build方法上使用,以将列表跳转到一个新的偏移量(使用SchedulerBinding.instance.addPostFrameCallback)。

问题在于,在我调用jumpto方法之后,标题被弄乱了(如果我手动滚动,标题将返回到正常位置)。

示例:

ezgif com-video-to-gif (1)

代码:

import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:sticky_headers/sticky_headers.dart';

double offset = 0;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration(seconds: 5)).then((_) => setState(() {
      offset = 3000;
    })).then((_) async => await Future.delayed(Duration(seconds: 5))).then((_) => setState(() {
      offset = 1000;
    })).then((_) async => await Future.delayed(Duration(seconds: 5))).then((_) => setState(() {
      offset = 5000;
    }));
  }

  @override
  Widget build(BuildContext context) {
    SchedulerBinding.instance.addPostFrameCallback((_) {
      print(offset);
      _scrollController.jumpTo(offset);
    });
    return Scaffold(body: Container(padding: EdgeInsets.only(top: 20),child: _buildList(context)));
  }

  Widget _buildList(BuildContext context) {
    return NotificationListener<ScrollNotification>(
        child: ListView.builder(
            controller: _scrollController,
            itemCount: 100,
            itemBuilder: (BuildContext context, int sectionIndex) => StickyHeader(
                header: Container(
                    height: 50,
                    alignment: Alignment.center,
                    color: Colors.blue,
                    child: Text("$sectionIndex")),

                content: ListView.builder(
                    itemCount: 10,
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    itemBuilder: (context, rowIndex) => Container(
                        color: Colors.white,
                        child: Text("$sectionIndex"))))),

        onNotification: (ScrollNotification scrollNotification) {
          offset = _scrollController.offset;
          print(offset);
          return true;
        });
  }
}

0 个答案:

没有答案