【自学 Flutter】20
if(wordsList[index]==loadFlag){
if (wordsList.length-1<100) {
loadWords();
return Container(
padding: EdgeInsets.all(20.0),
alignment: Alignment.center,
child: SizedBox(
width: 25.0,
height: 25.0,
child: CircularProgressIndicator(strokeWidth: 2.0,),
),
);
}else {
return Container(
padding: EdgeInsets.all(20.0),
alignment: Alignment.center,
child: Text("已全部加载完毕"),
);
}
}
return ListTile(
title: Text(wordsList[index]),
);
},
),
)
],
)
)
);
}
void loadWords(){
Future.delayed(Duration(seconds: 2)).then((e){
wordsList.insertAll(wordsList.length-1, generateWordPairs().take(20).map((e)=>e.asPascalCase).toList());
setState(() {});
});
}
}
2.引用单词包
a.在图中 3 的位置加入 english_words: ^3.1.0
b.在 main.dart 中导入包 import ‘package:english_words/english_words.dart’;
3.解释源代码
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
void main () => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
//加载列表信息的标识
static String loadFlag = "continue";
//单词列表储存,初始储存标识,用作后面数据继续加载
List<String> wordsList = [loadFlag];
//重写,初始化加载
@override
void initState() {
super.initState();
loadWords();
}
@override
Widget build(BuildContext context) {
Widget redDivider = Divider(color: Colors.red);
Widget blueDivider = Divider(color: Colors.blue);
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("无限加载列表"),),
body: Column(
children: <Widget>[
//利用 Colunm 和 Expanded 特性,使用 ListTile 作为列表表头
ListTile(title: Text("单词列表"),),
Expanded(
child: ListView.separated(
//数据数量
itemCount: wordsList.length,
separatorBuilder: (BuildContext context, int index){
return index % 2 == 0 ? redDivider:blueDivider;
},
itemBuilder: (BuildContext context, int in
dex){
//判断标识
if(wordsList[index]==loadFlag){
//小于 100 继续加载数据
if (wordsList.length-1<100) {
loadWords();
//返回一个圆形滚动条
return Container(
padding: EdgeInsets.all(20.0),
alignment: Alignment.center,
child: SizedBox(
width: 25.0,
height: 25.0,
//圆形滚动条
child: CircularProgressIndicator(strokeWidth: 2.0,),
),
);
}else {
//返回一个加载完的提示信息
return Container(
padding: EdgeInsets.all(20.0),
alignment: Alignment.center,
child: Text("已全部加载完毕"),
);
}
}
//显示单词在列表上
return ListTile(
title: Text(wordsList[index]),
);
},
),
)
],
)
)
);
}
评论