【发布时间】:2019-08-26 04:10:57
【问题描述】:
问题已于 4 月 10 日更新:
嗨! 我仍然卡住了,无法让它工作:(
我正在尝试制作一个应用程序,用户在导航到结果屏幕之前将总共回答 3 个问题。 为了显示问题的进度,将连续出现 3 个彩色容器。例如,该行最初为蓝色,但当用户回答正确时 - 该问题的容器将变为绿色,如果答案不正确,容器将变为红色。
我真的可以在这里使用一些进一步的帮助。
下面我用不同的颜色使代码尽可能简单,只是为了显示列表中的不同项目。
现在它在第一个问题上运行良好,但随后就停止了。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'listing 4',
theme: ThemeData(primarySwatch: Colors.blue),
home: FirstScreen(),
);
}
}
class FirstScreen extends StatefulWidget {
@override
_FirstScreenState createState() => _FirstScreenState();
}
class _FirstScreenState extends State<FirstScreen> {
int sum = 5;
String userAnswer;
String correction = "";
List<Color> colors = [Colors.blue, Colors.amber, Colors.pink];
submitPressed(int index) {
if (userAnswer == sum.toString()) {
setState(() {
correction = sum.toString();
colors[index] = Colors.green;
});
} else {
colors[index] = Colors.red;
}
}
Widget myListBuilder() {
return ListView.builder(
itemCount: 3,
itemBuilder: buildContainer,
);
}
Widget buildContainer(BuildContext context, int index) {
return Container(
child: Padding(
padding: const EdgeInsets.only(top: 10.0),
child: Container(
height: 20.0,
width: 15.0,
decoration: BoxDecoration(
color: colors[index], //this is the important line
borderRadius: BorderRadius.all(Radius.circular(8.0))),
),
));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Listing 4'),
),
body: Container(
child: Center(
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 10.0),
child: Text('Correct answer is 5',
style: TextStyle(fontSize: 20.0)),
),
Container(
width: 50.0,
child: TextField(
textAlign: TextAlign.center,
autofocus: true,
keyboardType: TextInputType.number,
onChanged: (val) {
userAnswer = val;
},
),
),
RaisedButton(
child: Text('Submit'),
onPressed: () {
submitPressed(0);
},
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
buildContainer(context, 0),
buildContainer(context, 1),
buildContainer(context, 2)
],
),
],
),
),
),
);
}
}
【问题讨论】:
-
您可以尝试创建一个长度与您拥有的盒子数量相同的颜色列表。当您在
ListView中构建一个框时,您将其颜色设置为它在列表中的位置。这样,当您更新列表中特定框的颜色时,它只会更新使用该位置颜色的框。 -
好的,非常感谢。我会尝试:)
-
嗯...可能是非常基本的东西,但是如何制作一个列表,然后让它一次更改一种颜色?我在想 List
correctionColor,其中 defautColor = blue,更新后:true = green 和 false = red。 -
我会创建一个
List<Color>,然后将它们全部设置为默认值。然后,您将编辑列表中的颜色以更改颜色。 -
是的,好主意。我现在有。我在最后一部分更新了我的问题(更多代码)。谢谢。
标签: list colors flutter containers increment