[英]Change Icon of Icon-Widget dynamically in Flutter
我是 Flutter 的新手,我想創建一個語音轉文本應用程序。 因此,我想要一個按鈕,其圖標會根據變量是真還是假而改變。 我正在使用一個浮動操作按鈕:
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
onPressed: () {
print(_isListening);
_isListening = !_isListening;
},
child: Icon(_isListening ? Icons.mic_rounded : Icons.mic_rounded ),
),
我的代碼的第一行是我的變量的定義:
bool _isListening = false;
“print(_isListening) 在控制台中給了我想要的 output,但在應用程序中,沒有任何變化。我做錯了什么嗎?
確保它是 StatefulWidget 並使用setState()通知框架此 object 的內部 state 已更改。 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. 請看下面的代碼:
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
onPressed: () {
print(_isListening);
setState(()=>_isListening = !_isListening);
},
child: Icon(_isListening ? Icons.mic_rounded : Icons.mic_off),
),
完整的工作代碼如下:
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),
),
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.