我无法使用自己的Class/Widget Question()
从question.dart
到main.dart
(错误代码位于正文后第三行):
import 'package:flutter/material.dart';
import './question.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
var questionIndex = 0;
// State of function that process data to UI
void _answerQuestion() {
setState(() {
questionIndex = questionIndex + 1;
});
print(questionIndex);
}
void _pangBawas() {
setState(() {
questionIndex = questionIndex - 1;
});
print(questionIndex);
}
// End of State
// This section is responsible for builing UI
@override
Widget build(BuildContext context) {
var questions = [
'What\'s your favorite color?',
'What\'s your favorite animal?',
'What\'s your favorite food?',
'What\'s your favorite color?',
'What\'s your favorite dress?',
'What\'s your favorite position?',
];
// Start of UI
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First App'),
),
body: Column(
children: [
Question( //ERROR: The element type 'Question' can't be assigned to the list type 'Widget'.
questions[questionIndex],
),
RaisedButton(
child: Text('Answer 1'),
onPressed: _answerQuestion,
),
RaisedButton(
child: Text('Answer 2'),
onPressed: () => _pangBawas,
),
RaisedButton(
child: Text('Answer 3'),
onPressed: () {
//....
print('Hi');
}),
],
),
),
);
// End of UI
}
}
这里没有错误,我只在Question()
文件上使用main.dart
时出错了
import 'package:/flutter/material.dart';
class Question extends StatelessWidget {
final String questionText;
Question(this.questionText);
@override
Widget build(BuildContext context) {
return Container(
child: Text(
questionText,
),
);
}
}
答案 0 :(得分:1)
使用插值可以解决一些错误,并在UI中向您显示错误。下面的代码可以正常工作:
___ ____
| |[____]
|___|[_][_]
答案 1 :(得分:0)
您可以添加行程运算符来检查Question类返回的Widget是否为null。发生这种情况是因为Column的子代小部件不能为空。
body: Column(
children: [
Question(questions[questionIndex]) == null
? SizedBox()
: Question(questions[questionIndex]),
这样,如果从Question类返回的小部件为空,则列将创建一个SizedBox而不是Container + Text。