Reputation: 65
I am new to Flutter and I wanted to create a speech to text application. Therefore I want a Button, whos icon changes depending if the a variable is true or false. I am using a floatingActionButton:
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
onPressed: () {
print(_isListening);
_isListening = !_isListening;
},
child: Icon(_isListening ? Icons.mic_rounded : Icons.mic_rounded ),
),
And the first line of my code is the definition of my variable:
bool _isListening = false;
The "print(_isListening) is giving me the desired output in the console, but in the app, nothing changes. Is there anything I am doing wrong?
Upvotes: 1
Views: 4163
Reputation: 6029
Make sure it's a StatefulWidget and use setState() to notify the framework that the internal state of this object has changed. Calling setState notifies the framework that the internal state of this object has changed in a way that might impact the user interface in this subtree, which causes the framework to schedule a build for this State object. Please see the code below:
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
onPressed: () {
print(_isListening);
setState(()=>_isListening = !_isListening);
},
child: Icon(_isListening ? Icons.mic_rounded : Icons.mic_off),
),
Full working code below :
import 'package:flutter/material.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: MyWidget());
}
}
class MyWidget extends StatefulWidget {
const MyWidget();
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
bool _isListening = true;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text("Flutter Demo"),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
onPressed: () {
print(_isListening);
setState(()=>_isListening = !_isListening);
},
child: Icon(_isListening ? Icons.mic_rounded : Icons.mic_off),
),
);
}
}
Upvotes: 2