我有一个小部件,该小部件调用一个函数以从API提取数据;提取函数完成后,它将调用另一个函数为其小部件构建一个表。这是代码:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() => runApp(MeTube());
// class
class MeTube extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new MeTubeState();
}
}
// state, component
class MeTubeState extends State<MeTube> {
bool _loading = true;
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
// primarySwatch: Colors(212121),
),
home: Scaffold(
appBar: AppBar(
title: Text('MeTube'),
centerTitle: false,
actions: <Widget>[
IconButton(
icon: Icon(Icons.refresh),
onPressed: () {_fetch();}, // call the fetch function (refresh)
)
],
),
body: Center(
child: _loading ? CircularProgressIndicator() : null /* I could load the ListView here
* and use the state to render each row
* but if there are 1,000+ rows, that
* would degrade the performance.
*/
),
)
);
}
// fetch data for the app
_fetch() async {
setState(() {_loading = true;}); // start the progress indicator
final String url = 'api.letsbuildthatapp.com/youtube/home_feed';
final res = await http.get('https://$url');
if (res.statusCode == 200) { // if successful, decode the json
final map = json.decode(res.body);
_build(map['videos'].length, map['videos']); // pass the # videos, and the videos
}
}
// build the data
_build(int rows, data) { /* MAKE EACH ROW */
MeTube().createElement().build( // create a ListView in the Class/Widget
ListView.builder(
itemCount: rows, /* number of rows to render, no need to setState() since this
* function (build) gets called, and the data is passed into it
*/
itemBuilder: (context, index) { // make each column for this class
Column(children: <Widget>[
Text(data[index]['name']), // render some Text and a Divider in each row
Divider()
]);
},
)
);
setState(() {_loading = false;}); // stop the progress indicator
}
}
build()
函数中的当前代码相当混乱,并显示错误。我该如何以编程方式将ListView和Rows插入到Widget中,而不是将所有视频推送到状态,然后运行代码以从状态中的所有这些值呈现一行?
答案 0 :(得分:1)
ListView.builder构造函数将在按需滚动到屏幕时创建项目。我想您不必担心性能。就像您对代码的注释一样进行操作。