Reputation: 9494
I am learning new Dart/Flutter and try to make my own exercise. I believe I am missing something fundamental here.
Problem:
My button is showing question mark. But I instantiate it with value already
Question:
How to instantiate button with given text?
import 'package:complete_guide/question.dart';
import 'package:flutter/material.dart';
import 'answer.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int index = 0;
List<String> questions = [
"How may I help you?",
"What is you favorite dog?"
];
void _answerQuestion(){
setState(() {
index = index + 1;
});
print(index);
}
void showText(inputText){
print(inputText);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Stay Strong")
),
body: Center(
child: Column(
children: [
Question(questions[index]),
Answer("iddqd", _answerQuestion),
Answer("idkfa", _answerQuestion),
Answer("show me the money", _answerQuestion),
],
),
),
)
);
}
}
class Answer extends StatelessWidget {
final Function selectHandler;
String answerText = "?";
Answer(answerText, this.selectHandler);
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: ElevatedButton(
child: Text(answerText),
onPressed: selectHandler,
)
);
}
}
class Question extends StatelessWidget {
final String questionText;
Question(this.questionText);
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: EdgeInsets.all(10),
child: Text(
this.questionText,
style: TextStyle(fontSize: 20, color: Colors.orange),
textAlign: TextAlign.center,
),
);
}
}
Upvotes: 0
Views: 56
Reputation: 17143
Please do not ignore analyzer warnings. They are there for a reason.
First, answerText
should be marked as final. It should not be initialized so that it can be assigned a value in the constructor. Finally, you need to use the this.
syntax that you've used for all of your other constructor parameters.
There is also no need of providing a default value of '?'
for answerText
because the constructor uses it as a required parameter, so that default value will never be used.
class Answer extends StatelessWidget {
final Function selectHandler;
final String answerText;
Answer(this.answerText, this.selectHandler);
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: ElevatedButton(
child: Text(answerText),
onPressed: selectHandler,
)
);
}
}
Upvotes: 1