Reputation: 1479
I am creating a button but I want it change the text every time I press it (e.g. on and off).
This is my button class.
class TextSend extends StatelessWidget {
String title;
Function onTap;
TextSend(this.title, this.onTap);
@override
Widget build(BuildContext context) {
return RaisedButton(
color: Colors.green,
disabledColor: Colors.grey,
textColor: Colors.white,
disabledTextColor: Colors.black38,
child: title,
onPressed: onTap,
);
}
}
This is the button instance, where I call it on another class:
TextSend('Button on', Navigator.push(context, MaterialPageRoute(builder: (context) => MQTTView()));),
Upvotes: 1
Views: 3171
Reputation: 1437
You need a StatefulWidget class. Flutter documentation has a really nice tutorial that shows an example similar to your problem.
Upvotes: 0
Reputation: 254
In order to change the text , you need to change the Stateless widget to Stateful Widget, because Stateless widget is only for static pages that doesn't change content.
after that in order to have a text into the button you need to give a Text widget as a child of the RaisedButton ,and not a String .
in order to change the text you have to call a function when the button is pressed, that function is gonna change the title variable and after that call "setState" function which is responsible of refreshing the page so that your changes can be displayed
here is your code modified and should do the job you want. if you miss something just make me know . thanks
import 'package:flutter/material.dart';
class TextSend extends StatefulWidget {
String title;
Function onTTap;
TextSend(this.title, this.onTTap);
@override
_TextSendState createState() => _TextSendState();
}
class _TextSendState extends State<TextSend> {
@override
Widget build(BuildContext context) {
return RaisedButton(
color: Colors.green,
disabledColor: Colors.grey,
textColor: Colors.white,
disabledTextColor: Colors.black38,
child: Text(widget.title),
onPressed: changeText, //
);
}
// method responsible of changing the text
changeText(){
setState(() {
widget.title='text changed';
});
}
}
Upvotes: 1