flutter - Flutter 显示数据并在点击时更改它
问题描述
我有一个任务,我需要显示来自 Apis 的值,然后按下凸起的按钮,然后将显示下一个值
这是我的代码
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
var _questions = new List<Questions>();
_getQuestions() {
API.getUsers().then((response) {
setState(() {
Iterable list = json.decode(response.body);
print(list);
print(list);
_questions = list.map((model) => Questions.fromJson(model)).toList();
print(_questions);
});
});
}
initState() {
super.initState();
_getQuestions();
}
final PrimaryColor = const Color(0xff404040);
final PreferredSizeWidget appBar = AppBar(
centerTitle: true,
title: Text(
'Would you Rather',
style: TextStyle(fontFamily: 'FredokaOne'),
),
backgroundColor: PrimaryColor,
);
double stackHeight = (MediaQuery.of(context).size.height -
appBar.preferredSize.height -
MediaQuery.of(context).padding.top);
double stackWidth = MediaQuery.of(context).size.width;
return Scaffold(
backgroundColor: Color(0xff404040),
appBar: appBar,
body: Column(
children: <Widget>[
Container(
child: Text('need to show value here'),
),
RaisedButton(
onPressed: on this press i need to change value,
child: Text('next'),
)
],
));
}
}
正如您在_questions
此处看到的 json 格式的数组,我需要打印该值,然后单击下一个值将显示。
从 api 获取数据是这样的
[
{
"rather": "Tea",
"would": "Coffe",
"wouldClick": 15,
"ratherClick": 12
},
{
"rather": "Oil",
"would": "Soap",
"wouldClick": 50,
"ratherClick": 12
},
{
"rather": "Soap",
"would": "Shaving Cream",
"wouldClick": 15,
"ratherClick": 12
}
]
我需要显示rather
数据中的值,点击时需要更改其他值rather
解决方案
您可以轻松地执行以下操作,
第一步:声明变量,保持点击次数,保持显示值
int currentValue = 0;
String value = "";
第 2 步:在 Click 事件中输入 if-else 条件并执行以下操作,
if (currentValue >= _questions.length) {
currentValue = 0;
setState(() {
value = items[currentValue].rather;
});
} else {
setState(() {
value = items[currentValue].rather;
});
currentValue ++;
}
第 3 步:在 display Text() 中设置声明的变量
child: Text(value)
全身小部件应该像,
body: Column(
children: <Widget>[
Container(
child: Text(value),
),
RaisedButton(
onPressed: (){
if (currentValue >= items.length) {
currentValue = 0;
setState(() {
value = items[currentValue];
});
} else {
setState(() {
value = items[currentValue];
});
currentValue ++;
}
}
child: Text('next'),
)
],
));
推荐阅读
- java - Jackson - 将 JSON 反序列化为类
- javascript - 在 react Native 中使用外部 API 呈现 Flatlist 的正确方法
- python - 熊猫在列表中正确的值
- java - 为 netbeans 8.2 运行 SQL 时出现词法错误
- regex - 通过在现有列上执行正则表达式来创建新列
- python - 如何将可变长度参数传递给另一个函数的参数?
- ada - Ada 202x 提案@限制理由?
- python - Python:无法在excel中格式化输出数据透视表的行
- java - Spring MVC - 尽管用户名和密码正确,但仍将我重定向到我的登录失败映射
- php - 由于连字符,pq_query 语法错误。我怎么写这个?