dart FlutterAngela Yu示例

h6my8fg2  于 2023-02-14  发布在  Flutter
关注(0)|答案(2)|浏览(90)

我想打印列表中的第一个元素,“firstques,”但是我也尝试使用final,得到了不同类型的错误,然后是所有类型的错误。

class _QuizPageState extends State<QuizPage> {
  List<Widget> scoreKeeper = [];

  List<String> questions = ["First ques", "seacond ques", "third ques"];
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        const Expanded(
          flex: 5,
          child: Padding(
            padding: EdgeInsets.all(10.0),
            child: Center(
              child: Text( 
                "example text"
                questions[0], //why its not displaying "first ques"
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 25.0,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
bvjveswy

bvjveswy1#

试试这个

class _QuizPageState extends State<QuizPage> {
    List<Widget> scoreKeeper = [];

    List<String> questions = ["First ques", "seacond ques", "third ques"];
    @override
    Widget build(BuildContext context) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          const Expanded(
            flex: 5,
            child: Padding(
              padding: EdgeInsets.all(10.0),
              child: Center(
                child: Text( 
                  questions[0], //why its not displaying "first ques"
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 25.0,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),

你得到错误的原因是文本小部件只接受一个字符串,而你传递了两个字符串给它。

dpiehjr4

dpiehjr42#

首先,您应该从Expanded小部件中删除const,因为您在Text中使用了一个变量questions[0]
我想提一下,为了可读性,最好使用questions.first,建议在使用questions.first之前检查列表是否为空,以防止可能的错误。
所以这是最终结果:

Column(
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    crossAxisAlignment: CrossAxisAlignment.stretch,
    children: <Widget>[
      Expanded(
        flex: 5,
        child: Padding(
          padding: const EdgeInsets.all(10.0),
          child: Center(
            child: Text(
              questions.first,
              //why its not displaying "first ques"
              textAlign: TextAlign.center,
              style: const TextStyle(
                fontSize: 25.0,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    ],
  ),

相关问题