반응형
설정된 글로벌 변수가 변경될 때 플러터에서 아이콘의 색상을 동적으로 업데이트할 수 있는 방법이 있습니까?
OnConnection에서 변경되는 글로벌 변수가 있습니다MQTT에 대한 콜백이 성공했습니다. 내 앱 바에는 변수를 확인한 다음 업데이트하여 탭할 때 색상을 변경하도록 할당할 수 있는 아이콘이 있다. 글로벌 변수가 바뀔 때마다 아이콘의 색상을 동적으로 변경할 수 있는 방법이 있는지 궁금합니다. 내가 이 일을 잘못하고 있는 것은 아닌지 모르겠다. 본질적으로, 나는 서버에 대한 내 연결이 변경될 때 아이콘이 변경되어 사용자가 연결되었는지 여부를 알리기를 원한다.
콜백 코드:
void onConnected() {
client.subscribe('topic', MqttQos.atMostOnce);
globals.isMqttConnected = true;
print('OnConnected client callback - Client connection was successful');}
현재 아이콘 코드:
child: GestureDetector(
onTap: () {
setState(() {});
},
child: (globals.isMqttConnected == true)
? const Icon(
Icons.bar_chart_rounded,
size: 26.0,
color: Colors.white,
)
: const Icon(
Icons.bar_chart_rounded,
size: 26.0,
color: Colors.grey,
),
),
OnDisconnected 콜백:
void onDisconnected() {
globals.isMqttConnected = false;
print('EXAMPLE::OnDisconnected client callback - Client disconnection');
if (client.connectionStatus!.disconnectionOrigin ==
MqttDisconnectionOrigin.solicited) {
print('EXAMPLE::OnDisconnected callback is solicited, this is correct');
} else {
print(
'EXAMPLE::OnDisconnected callback is unsolicited or none, this is incorrect - exiting');
// exit(-1);
}
if (pongCount == 3) {
print('EXAMPLE:: Pong count is correct');
} else {
print('EXAMPLE:: Pong count is incorrect, expected 3. actual $pongCount');
}
}
연결됨:
연결 끊김:
잘 설명하도록 노력하겠지만, 단순한 상태 관리로 사용하기 위해 가장 먼저 해야 할 일은 서비스를 만드는 것입니다. 이 경우 온커넥티드 및 온커넥티드 기능을 찾을 수 있습니다.
class OnlineService with ChangeNotifier { // to notify the listeners
bool _isConnected = false; // varible that gonna change
bool get isConnected => _isConnected; // getter
void onConnected() {
client.subscribe('topic', MqttQos.atMostOnce);
globals.isMqttConnected = true;
print('OnConnected client callback - Client connection was successful');
_isConnected = true; // now connected
notifyListeners(); // this is important to change the UI
}
void onDisconnected() {
globals.isMqttConnected = false;
print('EXAMPLE::OnDisconnected client callback - Client disconnection');
_isConnected = false; // now disconnected
notifyListeners(); // this is important to change the UI
if (client.connectionStatus!.disconnectionOrigin == MqttDisconnectionOrigin.solicited) {
print('EXAMPLE::OnDisconnected callback is solicited, this is correct');
} else {
print('EXAMPLE::OnDisconnected callback is unsolicited or none, this is incorrect - exiting'); // exit(-1);
}
if (pongCount == 3) {
print('EXAMPLE:: Pong count is correct');
} else {
print('EXAMPLE:: Pong count is incorrect, expected 3. actual $pongCount');
}
}
}
이제 나는 작은 데모를 만들었는데, 이것은 당신이 패키지를 다운로드해야 한다.
제가 다음에 한 일은 간단합니다. 버튼을 통해 연결 및 연결 해제를 시뮬레이션했습니다. 이제 서비스를 참조하는 변수나 함수를 호출해야 할 때 a를 사용하여 전역적으로 시작해야 합니다. 이렇게 하면 서비스가 모든 애플리케이션에 있습니다.
이러한 이유로 나는 다음과 같은 방법으로 초기화한다:
final OnlineService newsService = Provider.of<OnlineService>(context);
그것으로 나는 나의 함수들과 같은 방법으로 변수를 얻을 수 있다. 당신이 해야 할 일은 버튼을 점유하는 것이 아니라, 당신이 클라이언트가 연결할 때 그 함수들을 호출하고 당신은 그 변화를 볼 것이다.
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => OnlineService()), // set the service in all the app
],
child: MaterialApp(
title: 'Material App',
theme: myTheme,
debugShowCheckedModeBanner: false,
home: const HomePage(),
),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final OnlineService newsService = Provider.of<OnlineService>(context); // instance of the service
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
MaterialButton(
onPressed: () {
newsService.onConnected(); // connected
},
child: const Text("Connected"),
),
MaterialButton(
onPressed: () {
newsService.onDisconnected(); // disconnected
},
child: const Text("Disconnected"),
),
Center(
child: Icon(
Icons.bar_chart_rounded,
size: 26.0,
color: newsService.isConnected ? Colors.white : Colors.grey, // like this you change the color
),
),
],
);
}
}
반응형
'개발하자' 카테고리의 다른 글
svelte에서 내보낼 빌드 js 및 css 파일 이름을 지정하는 방법 (0) | 2023.09.07 |
---|---|
Kubernetes에서 배포 로그를 가져오는 방법은? (0) | 2023.09.07 |
펄럭임: Android Studio에서 패키지용 Android 모듈을 엽니다 (0) | 2023.09.06 |
오류 로드 상태 해결 방법: 액세스 거부: 액세스 거부 상태 코드: 테라폼 백엔드에 s3를 사용하려고 할 때 403? (0) | 2023.09.05 |
파이썬에서 셀레늄으로 헤드리스 마이크로소프트 엣지를 실행하는 방법? (0) | 2023.09.04 |