android - 如何以编程方式将文本元素添加到我的小部件/类?
问题描述
我有一个小部件,它调用一个函数来从 API 获取数据;fetch 函数完成后,它调用另一个函数为其小部件构建一个表。这是代码:
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 中,而不是将所有视频推送到状态,然后运行代码以从状态中的所有这些值呈现一行?
解决方案
ListView.builder 构造函数将创建项目,因为它们像按需滚动到屏幕上一样。我想你不需要担心性能。像你对代码的评论一样去做。
推荐阅读
- java - java.lang.IllegalArgumentException:未知实体:
- typescript - 如何用参数化类型递归替换打字稿原语
- python - 尝试制作用户输入的莫尔斯电码转换器
- jmeter - 在 JMeter 中将当前时间转换为 GMT 和 EPOCH
- javascript - 如何在 JavaScript For 循环中故意触发索引越界错误?
- typescript - 使用 ts-node 时使用 Mongoose 连接到本地 mongodb 时出错?
- google-sheets - Google 表格的 Lambda 函数
- docker - python代码在kubernetes pod中运行时如何获取客户端IP地址?
- visual-studio - 在 VS Code 中搜索回车符 '\r'
- html - 我的代码编辑器或继承代码有问题吗?