📜  Flutter – 在 ListView 中向下滚动到列表的底部或顶部

📅  最后修改于: 2022-05-13 01:54:19.714000             🧑  作者: Mango

Flutter – 在 ListView 中向下滚动到列表的底部或顶部

在本教程中,我们将学习如何在Flutter向下滚动到ListView的底部。向下滚动到列表底部非常无聊,因此这里提供了一种直接滚动到列表底部或顶部的方法。

项目设置:

下面是一个入门代码,以便您可以按照本教程进行操作。此代码生成一个包含 100 个项目的列表的应用程序。

Dart
import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Geeks For Geeks',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: MyHomePage(title: 'Geeks For Geeks'),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;
  
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
        
      // Floating action button. Functionality to be implemented
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        isExtended: true,
        tooltip: "Scroll to Bottom",
        child: Icon(Icons.arrow_downward),
      ),
        
      // Simple List of 100 items
      body: ListView.builder(
        itemCount: 100,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text("Item ${index + 1}"),
          );
        },
      ),
    );
  }
}


Dart
ScrollController listScrollController = ScrollController();


Dart
controller: listScrollController,


Dart
// We will jump to the bottom of the list
  
onPressed: () {
  if (listScrollController.hasClients) {
    final position = listScrollController.position.maxScrollExtent;
    listScrollController.jumpTo(position);
  }
},


Dart
listScrollController.hasClients


Dart
final position = listScrollController.position.maxScrollExtent;


Dart
listScrollController.jumpTo(position);


Dart
// We will reach the bottom of list within a duration of 
// 3 seconds animating down the ListView
  
listScrollController.animateTo(
  position,
  duration: Duration(seconds: 3),
  curve: Curves.easeOut,
);


Dart
// Floating action button is implemented with the above functionality 
// and onPressed triggers the function
  
floatingActionButton: FloatingActionButton(
  onPressed: () {
    if (listScrollController.hasClients) {
      final position = listScrollController.position.minScrollExtent;
      listScrollController.animateTo(
        position,
        duration: Duration(seconds: 3),
        curve: Curves.easeOut,
      );
    }
  },
  isExtended: true,
  tooltip: "Scroll to Top",
  child: Icon(Icons.arrow_upward),
),


Dart
import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Geeks For Geeks',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: MyHomePage(title: 'Geeks For Geeks'),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;
  
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State {
  ScrollController listScrollController = ScrollController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
        
      // Floating action button implemented with the
      // auto scroll function to the bottom of list 
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          if (listScrollController.hasClients) {
            final position = listScrollController.position.maxScrollExtent;
            listScrollController.animateTo(
              position,
              duration: Duration(seconds: 3),
              curve: Curves.easeOut,
            );
          }
        },
        isExtended: true,
        tooltip: "Scroll to Bottom",
        child: Icon(Icons.arrow_downward),
      ),
        
      // ListView with 100 list items
      body: ListView.builder(
          
        // Scroll Controller for functionality
        controller: listScrollController,
        itemCount: 100,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text("Item ${index + 1}"),
          );
        },
      ),
    );
  }
}


运行代码,结果如下。

入门代码

执行:

正如您所看到的,我们的FloatingActionButton不起作用,因为在onPressed字段中没有为其分配任何函数。首先,我们需要一个ScrollController来控制我们的ListView 。所以创建一个ScrollController。



Dart

ScrollController listScrollController = ScrollController();

现在将此ScrollController分配给ListView控制器字段

Dart

controller: listScrollController,

现在来到FloatingActionButtononPressed()字段。

这里我们将使用以下代码:

Dart

// We will jump to the bottom of the list
  
onPressed: () {
  if (listScrollController.hasClients) {
    final position = listScrollController.position.maxScrollExtent;
    listScrollController.jumpTo(position);
  }
},

我们首先检查是否可以使用ScrollController的成员进行通信

Dart



listScrollController.hasClients

如果未选中,我们将收到运行时错误。上面的代码返回一个布尔值。现在进入下一部分,我们要求ScrollController的最大滚动范围。

Dart

final position = listScrollController.position.maxScrollExtent;

这只是意味着我们通过ScrollController请求ListView 中的最后一个位置。然后,我们要求ScrollController使用jumpTo函数移动我们在上面得到的位置。

Dart

listScrollController.jumpTo(position);

现在运行代码,您将看到以下结果。

向下滚动列表

所以我们已经成功地到达了我们列表的底部。

现在你可能认为如果不突然移动到列表的底部会很好,我们会很容易地去。所以同样可以使用animateTo函数来实现。

jumpTo代码替换为以下代码:

Dart

// We will reach the bottom of list within a duration of 
// 3 seconds animating down the ListView
  
listScrollController.animateTo(
  position,
  duration: Duration(seconds: 3),
  curve: Curves.easeOut,
);

现在再次运行该应用程序。您将看到以下结果。



动画滚动

我们已经学习了如何向下滚动列表,现在我们将学习如何滚动到ListView的顶部。

不但得不到maxScrollExtent的,我们现在从ScrollController使用minScrollExtent而仅仅意味着ListView控件的顶部位置。

这是代码,不要忘记更改图标:

Dart

// Floating action button is implemented with the above functionality 
// and onPressed triggers the function
  
floatingActionButton: FloatingActionButton(
  onPressed: () {
    if (listScrollController.hasClients) {
      final position = listScrollController.position.minScrollExtent;
      listScrollController.animateTo(
        position,
        duration: Duration(seconds: 3),
        curve: Curves.easeOut,
      );
    }
  },
  isExtended: true,
  tooltip: "Scroll to Top",
  child: Icon(Icons.arrow_upward),
),

现在再次运行该应用程序。

滚动列表视图的顶部

完整的源代码:

Dart

import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Geeks For Geeks',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: MyHomePage(title: 'Geeks For Geeks'),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;
  
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State {
  ScrollController listScrollController = ScrollController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
        
      // Floating action button implemented with the
      // auto scroll function to the bottom of list 
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          if (listScrollController.hasClients) {
            final position = listScrollController.position.maxScrollExtent;
            listScrollController.animateTo(
              position,
              duration: Duration(seconds: 3),
              curve: Curves.easeOut,
            );
          }
        },
        isExtended: true,
        tooltip: "Scroll to Bottom",
        child: Icon(Icons.arrow_downward),
      ),
        
      // ListView with 100 list items
      body: ListView.builder(
          
        // Scroll Controller for functionality
        controller: listScrollController,
        itemCount: 100,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text("Item ${index + 1}"),
          );
        },
      ),
    );
  }
}

输出:

滚动到列表底部

滚动到列表顶部

结论:

在本教程中,我们学习了 ListView 的一个非常有趣的功能,您可能在许多网站和博客上都遇到过。所以现在您也可以在您的应用程序中实现相同的功能。