Flutter ListView.builder结结巴巴并跳到滚动顶部

时间:2019-02-06 01:27:40

标签: firebase asynchronous dart flutter google-cloud-firestore

从列表的中途向下滚动可使页面跳至顶部。我正在使用Flutter和Firestore,以及StreamBuilder来获取数据。

我尝试过更改滚动体,设置占位符,但这似乎无济于事。

  StreamBuilder<QuerySnapshot>(
    // Create a stream listening to the posts collection
    stream: widget.firestore
        .collection('posts')
        .orderBy('sequence', descending: false)
        .snapshots(),
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
      // When we don't have data yet (!...hasData), display the text "Loading..."
      if (!snapshot.hasData) return const Text('Loading...');
      final int messageCount = snapshot.data.documents.length;

      // When data is availible, load
      return new ListView.builder(
        //padding: EdgeInsets.all(3.0),
        itemCount: messageCount,
        itemBuilder: (_, int index) {
          final DocumentSnapshot document = snapshot.data.documents[index];
          if (document["type"] == "standard")
            return StandardCard(widget.firestore, document.documentID);
          else if (document["type"] == "text")
            return TextCard(widget.firestore, document.documentID);
          else if (document["type"] == "video")
            return VideoCard(widget.firestore, document.documentID);
          else
            return Card(
              // Database is incorrect
              child: Center(
                child: Text("[Missing sufficient information]"),
              ),
            );
        },
      );
    },
  ),

当您向下滚动时,它可以平滑滚动,但在向上滚动时会急于向上滚动。

这是一个独立的例子。

import 'dart:math';

import 'package:flutter/material.dart';

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

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

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  stream() async* {
    yield ObjectHasFuture();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: StreamBuilder(
            stream: stream(),
            builder: (BuildContext context, snapshot) {
              if (!snapshot.hasData) return const Text('Loading...');
              return ListView.builder(
                itemBuilder: (_, int index) {
                  return Card(
                    child: snapshot.data,
                  );
                },
              );
            }));
  }
}

class ObjectHasFuture extends StatelessWidget {
  data() async {
    await Future.delayed(Duration(seconds: Random().nextInt(2)));
    return Container(
      height: 250,
      color: Colors.green,
      child: Center(
        child: Text(Random().nextInt(10000).toString()),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: data(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) return const Text("Loading");

          return snapshot.data;
        });
  }
}

3 个答案:

答案 0 :(得分:0)

您是在调试模式还是发布模式下执行此操作?调试模式有时会显示出奇怪的工件,这些工件会在最终版本中消失。

答案 1 :(得分:0)

如果要处理列表项数量很少的静态数据,则可以使用以下方法加快列表的速度

ListView(
          addAutomaticKeepAlives: true,
          ...
)

答案 2 :(得分:0)

给它一个scrollController:

Listview.builder(
  controller: ScrollController(),
  //
)