【问题标题】:The element type '{0}' can't be assigned to the list type '{1}' flutter元素类型“{0}”无法分配给列表类型“{1}”颤动
【发布时间】:2021-11-25 15:24:39
【问题描述】:

我一直在尝试学习有关 udemy 的颤振课程,但在代码中它给了我这个错误:

元素类型“问题”不能分配给列表类型“小部件”。

这是 main.dart 中的代码:

    class _MyAppState extends State<MyApp> {
  int _qIndex = 0;

  void _ansQ() {
    setState(() {
      _qIndex++;
    });
    print('Answer Chosen');
  

   print(_qIndex);   }
 
   @override   Widget build(BuildContext context) {
     var questions = [
       'What\'s your favorite food?',
       'What\'s your favorite color?'
     ];
     return MaterialApp(
       home: Scaffold(
           appBar: AppBar(
             title: Text('My First Flutter App'),
           ),
           body: Column(
             children: [
               Question(questions[_qIndex]), //This is the line that gives me the error
               RaisedButton(child: Text('Answer 1'), onPressed: _ansQ),
               RaisedButton(
                 child: Text('Answer 2'),
                 onPressed: () => print('Answer 2 chosen')),
               RaisedButton(child: Text('Answer 3'), onPressed: _ansQ)
             ]
           )
        ),
     );   } }

这是 question.dart 中的代码:

import 'package:/flutter/material.dart';

class Question extends StatelessWidget {
  final String questionText;
  const Question(this.questionText);

  @override
  Widget build(BuildContext context) {
    return Text(questionText);
  }
}

如果可以,你能帮帮我吗?

【问题讨论】:

  • 升级你的flutter版本,它不会给我错误。
  • import 中的question.dart 行有一个无关的/。在关注依赖它的文件中的错误之前,请确保修复 question.dart 中的所有错误。

标签: android flutter dart visual-studio-code widget


【解决方案1】:

尝试像这样在导入后添加as qus

import 'package:'PATH'/Question.dart' as qus;

然后使用

Column(
             children: [
              qus.Question(questions[_qIndex]), //This is the line that gives me the error
               RaisedButton(child: Text('Answer 1'), onPressed: _ansQ),
               RaisedButton(
                 child: Text('Answer 2'),
                 onPressed: () => print('Answer 2 chosen')),
               RaisedButton(child: Text('Answer 3'), onPressed: _ansQ)
             ]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2019-11-29
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    相关资源
    最近更新 更多