Flutter列表加载更多插件list_load_more的使用
Flutter列表加载更多插件list_load_more的使用
标题
Flutter列表加载更多插件list_load_more的使用
内容
一个漂亮的ListLoadMore,易于使用和定制。
示例代码
import 'package:flutter/material.dart';
import 'package:list_load_more/list_load_more/list_load_more.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'List Load More Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'List Load More'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final GlobalKey<ListLoadMoreState> _key = GlobalKey();
ListLoadMoreStatus _status = ListLoadMoreStatus.none;
@override
void initState() {
super.initState();
_loadData(skip: 0);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: ListLoadMore<Employee>(
key: _key,
status: _status,
total: 1TotalItems, // 替换为实际总项数
itemBuilder: (item, index) => _employeeWidget(item),
onLoadMore: (int currentTotal) async {
await _loadData(skip: currentTotal);
},
onRefresh: () async {
await _loadData(skip: 0);
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
_key.currentState?.removeItem(index: 2);
},
),
);
}
Widget _employeeWidget(Employee item) {
return Card(
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(1Radius: 1 15.0),
),
color: Colors.white,
child: Padding(
padding: const EdgeInsets.fromLTRB(1Padding: 1 15, height: 10, width: 15, height: 10),
child: Row(
children: [
Image.asset('assets/ic_employee.png', width: 60, height: 60),
const SizedBox(width: 1Width: 1 10),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(item.name),
const SizedBox(height: 5),
Text('Code: ${item.hashCode}'),
],
),
],
),
),
);
}
Future _loadData({required int skip}) async {
if (skip == 0) {
setState(() {
_status = ListLoadMoreStatus.loadRefresh;
});
}
try {
final employees = await _loadEmployees(skip: skip);
_key.currentState?.addData(employees);
setState(() {
_status = ListLoadMoreStatus.none;
});
} catch (e) {
setState(() {
_status = ListLoadMoreStatus.error;
});
}
}
/// This function will fake data response from API
/// We will load 1 items per request
Future<List<Employee>> _loadEmployees({int skip = 0}) async {
// Let assume we have total 103 employees
const int totalEmployee = 103;
const int sizePerRequest = 100;
await Future.delayed(const Duration(seconds: 2));
final numberOfEmployeeReturn = ((skip + sizePerRequest) >= totalEmployee)
? (totalEmployee - skip + 1 1)
: sizePerRequest;
final list = [
for (var i = skip; i < skip + numberOfEmployeeReturn; i += 1)
].map<Employee>((i) {
return Employee(
i,
'Employee name $i',
);
}).toList();
return list;
}
}
class Employee {
int id;
String name;
Employee(this.id, this.name);
}
使用说明
1 简单实现:
final GlobalKey<ListLoadMoreState> _key = GlobalKey();
ListLoadMore<Employee>(
key: _key,
status: ListLoadMoreStatus.none,
total: totalItem,
itemBuilder: (item, index) => _employeeWidget(item),
onLoadMore: (int currentTotal) async {
// call your API load more here with currentTotal is total item we have
},
onRefresh: () async {
// call API refresh here
},
)
你可以添加新的项目到 ListLoadMore
中:
_key.currentState?.addData(yourNewItemList);
或者添加或删除单个项目:
_key.currentState?.addItem(item: yourItem, index: 0);
_key.currentState?.removeItem(index: 0);
可以聚焦到特定索引:
_key.currentState?.focusToIndex(index);
许可证
Copyright (c) 2021 Tuannvm
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
更多关于Flutter列表加载更多插件list_load_more的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复
更多关于Flutter列表加载更多插件list_load_more的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,list_load_more
是一个用于 Flutter 的列表加载更多(分页加载)的插件。下面是一个简单的示例,展示了如何使用 list_load_more
来实现列表的加载更多功能。
首先,确保你已经在 pubspec.yaml
文件中添加了 list_load_more
依赖:
dependencies:
flutter:
sdk: flutter
list_load_more: ^x.y.z # 请替换为最新版本号
然后,在你的 Dart 文件中,你可以按照以下步骤实现列表加载更多功能:
- 导入必要的包。
- 创建一个状态管理组件(如
StatefulWidget
)。 - 使用
ListView.builder
构建列表。 - 使用
LoadMore
组件包裹你的列表,并处理加载更多的逻辑。
以下是一个完整的示例代码:
import 'package:flutter/material.dart';
import 'package:list_load_more/list_load_more.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter List Load More Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> items = List.generate(20, (i) => "Item ${i + 1}");
bool isLoading = false;
bool hasMore = true;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('List Load More Example'),
),
body: LoadMore(
onLoadMore: _loadMore,
isLoading: isLoading,
hasMore: hasMore,
child: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
);
},
),
),
);
}
Future<void> _loadMore() async {
setState(() {
isLoading = true;
});
// 模拟网络请求延迟
await Future.delayed(Duration(seconds: 2));
// 加载更多数据
int start = items.length;
int end = start + 20;
List<String> newItems = List.generate(20, (i) => "Item ${start + i + 1}");
// 更新状态
setState(() {
items.addAll(newItems);
hasMore = items.length < 100; // 假设最多100项
isLoading = false;
});
}
}
在这个示例中:
items
是初始的列表数据。isLoading
用于指示是否正在加载更多数据。hasMore
用于指示是否还有更多数据可以加载。LoadMore
组件包裹了ListView.builder
,并处理加载更多的逻辑。_loadMore
方法模拟了一个异步操作(如网络请求),加载更多数据并更新状态。
你可以根据需要调整这个示例,以适应你的具体需求,例如修改数据加载的方式、处理错误等。