Instantiate child button with given value, but it is not changed - flutter

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,
),
);
}
}

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,
)
);
}
}

Related

How to change scaffold colour randomly on clicking separate file's gesturdetector button

I have made two files... one is main.dart and other is homescreen.dart. Homescreen is for scaffold body which is created separately. Now there is a button in home screen for changing colour of scaffold. How to do this?
The main purpose is to know access scaffold from other stateful widget class file...
main.dart
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: SafeArea(child: Scaffold(body: HomeScreen(),)),
);
}
}
homescreen.dart
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){
//My query is to PLACE CODE HERE TO CHANGE SCAFFOLD COLOR ON CLICKING
},
child: Center(
child: Container(
color: Colors.red,
height: 60,
width: 200,
child: Center(child: Text('Change Color',)),
),
),
);
}
}
Try this:
main.dart
import 'package:flutter/material.dart';
import 'home.dart';
import 'dart:math' as math;
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Color _color = Colors.white;
void changeColor(){
setState(() {
_color = Color((math.Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1.0);
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: SafeArea(child: Scaffold(
backgroundColor: _color,
body: HomeScreen(changeColor: changeColor,),)),
);
}
}
home.dart
import 'package:flutter/material.dart';
class HomeScreen extends StatelessWidget {
VoidCallback? changeColor;
HomeScreen({Key? key, this.changeColor}) : super(key: key);
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: changeColor,
child: Center(
child: Container(
color: Colors.red,
height: 60,
width: 200,
child: const Center(
child: Text(
'Change Color',
),
),
),
),
);
}
}
You can do it like this :
/// EDIT :
I edit it to get the Color random
import 'dart:math' as math;
class _MyAppState extends State<MyApp> {
Color _newColor = Colors.white; // variable with the color you want to change
final rnd = math.Random(); // random
Color getRandomColor() =>
Color(rnd.nextInt(0xffffffff)); // little function to get the color random
void _changeNewColor() { // function that you are going to send to yout HomeScreen
setState(() {
_newColor = getRandomColor();
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: HomeScreen(change: _changeNewColor), // function
backgroundColor: _newColor, // here the variable
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({
Key? key,
this.change,
}) : super(key: key);
final Function()? change; // instance and get the funct
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: change,
child: Center(
child: Container(
color: Colors.red,
height: 60,
width: 200,
child: const Center(
child: Text(
'Change Color',
)),
),
),
);
}
}

The argument type 'Function' can't be assigned to the parameter type 'void Function()?

I am getting this error on answer.dart
"lib/answer.dart:15:20: Error: The argument type 'Function' can't be assigned to the parameter type 'void Function()?'."
Here are the files:
main.dart
import 'package:flutter/material.dart';
import 'Questions.dart';
import 'answer.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _MyAppState();
// ignore: dead_code
throw UnimplementedError();
}
}
class _MyAppState extends State<MyApp> {
var _questionIndex = 0;
var questions = [
'what\'s your fav color?',
'what\'s your fav Food?',
'what\'s your fav Animal?'
];
void _answerQuestion() {
setState(() {
_questionIndex++;
if (_questionIndex >= questions.length) _questionIndex = 0;
});
print(_questionIndex);
print(questions.length);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My Flutter App'),
),
body: Column(
children: [
Question(questions[_questionIndex]),
Answer(_answerQuestion),
Answer(_answerQuestion),
Answer(_answerQuestion),
],
),
),
);
}
}
answer.dart
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
final Function selectHandler;
Answer(this.selectHandler);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: ElevatedButton(
child: Text('Ans 1'),
onPressed: selectHandler,
style: ElevatedButton.styleFrom(
primary: Colors.red,
),
),
);
}
}
Questions.dart
import 'package:flutter/material.dart';
class Question extends StatelessWidget {
final String questionText;
Question(this.questionText);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: EdgeInsets.all(10),
padding: EdgeInsets.all(10),
child: Text(
questionText,
style: TextStyle(fontSize: 28),
textAlign: TextAlign.center,
),
);
}
}
Now I have tried to look at the logic, constructor is properly defined in the answer.dart file and it has been handeled well in the main.dart as well.
I am still learning and running out of options to solve this error.
can anyone please help to resolve this error.
Change it to this:
onPressed: ()=> selectHandler()

Error: The argument type 'Function' can't be assigned to the parameter type 'void Function()?'.'Function' is from 'dart:core'.onPressed: selectHandler

main.dart
import 'package:flutter/material.dart';
import './questions.dart';
import './answer.dart';
void main() {
runApp(AskMe());
}
class AskMe extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _AskMeState();
}
}
class _AskMeState extends State<AskMe> {
var _next_ques = 0;
void _Response() {
setState(() {
_next_ques += 1;
});
print(_next_ques);
}
#override
Widget build(BuildContext context) {
var questions = ["What is your Name ?", "What is your favourite color ?"];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Ask Me"),
),
body: Column(
children: [
Questions(questions[_next_ques]),
Answer(_Response),
Answer(_Response),
Answer(_Response),
],
),
),
);
}
}
questions.dart
import 'package:flutter/material.dart';
class Questions extends StatelessWidget {
final String questions;
Questions(this.questions);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: EdgeInsets.all(20),
child: Text(
questions,
style: TextStyle(fontSize: 28),
textAlign: TextAlign.center,
),
);
}
}
answer.dart
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
final Function selectHandler;
Answer(this.selectHandler);
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: EdgeInsets.all(10),
child: RaisedButton(
color: Colors.blueGrey,
child: Text("Question 1"),
onPressed: selectHandler,
),
);
}
}
The above code is for basic app that consists of 3 buttons for the questions shown as textview and clicking on button will display next question. The issue i'm facing is while making custom dart function in answer.dart i'm not able to call the pointer to the function _Response which is present in main.dart as it gives the error mentioned in the title. Thanks for the help.
Define function type like this:
class Answer extends StatelessWidget {
final Function() selectHandler;
...

Flutter: How To Change/Refresh State From Another Widget

I am trying to have a global integer that is displayed in a widget and then is updated by something (a button click or something) from another widget. All of the other ways i have tried don't work. What is the best way to do this?
Stack overflow says i have too much code so more text more text more text
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ScoreDisplay(),
PointButton(),
],
),
),
),
),
);
}
int score = 0;
class ScoreDisplay extends StatefulWidget {
#override
_ScoreDisplayState createState() => _ScoreDisplayState();
}
class _ScoreDisplayState extends State<ScoreDisplay> {
#override
Widget build(BuildContext context) {
return Center(
child: Container(
child: Text(
'Score: $score',
),
),
);
}
}
class PointButton extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Center(
child: Container(
child: RaisedButton(
//onPressed: //increment score,
),
),
);
}
}
You need to implement some kind of State Management for that.
Here are two basic ways to implement such a feature: with a StatefulWidget and with Riverpod.
1. With a StatefulWidget
I extracted your Scaffold as a StatefulWidget maintaining the score of your application.
I then use ScoreDisplay as a pure StatelessWidget receiving the score as a parameter. And your PointButton is also Stateless and call the ScorePage thanks to a simple VoidCallback function.
Full source code:
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: ScorePage(),
),
);
}
class ScorePage extends StatefulWidget {
const ScorePage({
Key key,
}) : super(key: key);
#override
_ScorePageState createState() => _ScorePageState();
}
class _ScorePageState extends State<ScorePage> {
int score = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ScoreDisplay(score: score),
PointButton(onIncrement: () => setState(() => score++)),
],
),
),
);
}
}
class ScoreDisplay extends StatelessWidget {
final int score;
const ScoreDisplay({Key key, this.score}) : super(key: key);
#override
Widget build(BuildContext context) {
return Center(
child: Container(
child: Text(
'Score: $score',
),
),
);
}
}
class PointButton extends StatelessWidget {
final VoidCallback onIncrement;
const PointButton({Key key, this.onIncrement}) : super(key: key);
#override
Widget build(BuildContext context) {
return Center(
child: Container(
child: ElevatedButton(
onPressed: () => onIncrement?.call(),
child: Text('CLICK ME'),
),
),
);
}
}
2. With Riverpod
Create a StateProvider:
final scoreProvider = StateProvider<int>((ref) => 0);
Watch the StateProvider:
final score = useProvider(scoreProvider).state;
Update the StateProvider
context.read(scoreProvider).state++
Full Source Code
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
void main() {
runApp(
ProviderScope(
child: MaterialApp(
home: Scaffold(
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ScoreDisplay(),
PointButton(),
],
),
),
),
),
),
);
}
int score = 0;
class ScoreDisplay extends HookWidget {
#override
Widget build(BuildContext context) {
final score = useProvider(scoreProvider).state;
return Center(
child: Container(
child: Text(
'Score: $score',
),
),
);
}
}
class PointButton extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Center(
child: Container(
child: ElevatedButton(
onPressed: () => context.read(scoreProvider).state++,
child: Text('CLICK ME'),
),
),
);
}
}
final scoreProvider = StateProvider<int>((ref) => 0);
Check Riverpod Website for more info and more advanced use cases.
But you have many more flavors of State Management available.
The best example is to use "provider" package which can be found on www.pub.dev
It is very easy state management package that can help You solve this problem. Keep in my that provider instead of setState() uses notifyListener()

How to set the state of a stateful widget from a child stateless widget

Okay, so just to warn you, I'm 15 and I'm a complete flutter noob. This is my first ever project, so excuse the probably dumb question, and please go easy on me.
I have this stateful widget (ride) where the body is one of the child stateless widgets defined in _children. The if statement just changes between the 1st and 2nd child widgets depending on if the user has connected a BT device (that part is irrelevant).
What I need to do is set the state from the inside of the MaterialButton found on ln 68 so that ride shows the riding stateless widget, but obviously I can't change the state from inside startRide because it's a stateless widget. How would I go about doing this?
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' ;
import 'results.dart';
import 'settings.dart';
class ride extends StatefulWidget {
#override
_rideState createState() => _rideState();
}
class _rideState extends State<ride> {
int _currentState = 0;
final List<Widget> _children = [
notConnected(),
startRide(),
riding(),
];
bool connected = checkBT(); // Function defined in settings.dart
#override
Widget build(BuildContext context) {
if (connected == true){
_currentState = 1;
setState((){_currentState;});
}
return _children[_currentState];
}
}
class notConnected extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height:180,
padding: EdgeInsets.fromLTRB(40, 0, 40, 0),
child: Center(
child: Text(
"Oops! Looks like your phone isn’t connected to your bluetooth device.",
style:Theme.of(context).textTheme.bodyText2,
textAlign: TextAlign.center,
),
),
),
);
}
}
class startRide extends StatelessWidget {
AudioPlayer _audioPlayer = AudioPlayer();
AudioCache player = AudioCache();
#override
Widget build(BuildContext context) {
return Scaffold(
body:Center(
child: Container(
width: 200,
height: 80,
child: MaterialButton(
onPressed:(){
player.play("beeps.mp3");
// I NEED TO SET THE STATE OF RIDE HERE
},
child: Text(
"Start!",
style: Theme.of(context).textTheme.headline1,
),
color: Colors.red[500],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(40.0)),
),
),
),
),
);
}
}
class riding extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(); //not finished writing this yet
}
}
I'm probably going about doing this in completely the wrong way, but I've come from python so it's very different. Any help would be greatly appreciated :)
You can create callback, i.e passing function
Here is a sample code
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' ;
import 'results.dart';
import 'settings.dart';
class ride extends StatefulWidget {
#override
_rideState createState() => _rideState();
}
class _rideState extends State<ride> {
int _currentState = 0;
final List<Widget> _children = [
notConnected(),
startRide((){
// you can setState((){}) here
}),
riding(),
];
bool connected = checkBT(); // Function defined in settings.dart
#override
Widget build(BuildContext context) {
if (connected == true){
_currentState = 1;
setState((){_currentState;});
}
return _children[_currentState];
}
}
class notConnected extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height:180,
padding: EdgeInsets.fromLTRB(40, 0, 40, 0),
child: Center(
child: Text(
"Oops! Looks like your phone isn’t connected to your bluetooth device.",
style:Theme.of(context).textTheme.bodyText2,
textAlign: TextAlign.center,
),
),
),
);
}
}
class startRide extends StatelessWidget {
AudioPlayer _audioPlayer = AudioPlayer();
AudioCache player = AudioCache();
Function callback;
startRide(Function callback){
this.callback = callback;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body:Center(
child: Container(
width: 200,
height: 80,
child: MaterialButton(
onPressed:(){
player.play("beeps.mp3");
// I NEED TO SET THE STATE OF RIDE HERE
// callback function
callback();
},
child: Text(
"Start!",
style: Theme.of(context).textTheme.headline1,
),
color: Colors.red[500],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(40.0)),
),
),
),
),
);
}
}
class riding extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(); //not finished writing this yet
}
}
Edit :- Test code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Test(),
);
}
}
class Test extends StatefulWidget {
#override
_Test createState() => _Test();
}
class _Test extends State<Test> {
int current = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
body: root(),
);
}
Widget root() {
return Container(
child: TestingStateless((){
setState(() {
current++;
print(current);
});
}),
);
}
}
// ignore: must_be_immutable
class TestingStateless extends StatelessWidget{
Function func;
TestingStateless(Function func){
this.func = func;
}
#override
Widget build(BuildContext context) {
return InkWell(
onTap: (){
func();
},
child: Container(
height: 50,
color: Colors.green,
child: Text('TESTING'),
),
);
}
}