#flutter #dart
Вопрос:
Я пытаюсь использовать приведенный ниже плагин flutter, связанный с данными о состоянии телефона для пользователя
https://pub.dev/packages/cell_info
аналогично приведенному ниже встроенному плагину kotlin
https://github.com/mroczis/netmonster-core
так же, как и в примере в плагине fluter:
import 'dart:async';
import 'dart:convert';
import 'package:cell_info/CellResponse.dart';
import 'package:cell_info/cell_info.dart';
import 'package:cell_info/models/common/cell_type.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
CellsResponse _cellsResponse;
@override
void initState() {
super.initState();
initPlatformState();
}
String currentDBM = "";
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
CellsResponse cellsResponse;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
String platformVersion = await CellInfo.getCellInfo;
final body = json.decode(platformVersion);
cellsResponse = CellsResponse.fromJson(body);
CellType currentCellInFirstChip = cellsResponse.primaryCellList[0];
if (currentCellInFirstChip.type == "LTE") {
currentDBM =
"LTE dbm = " currentCellInFirstChip.lte.signalLTE.dbm.toString();
} else if (currentCellInFirstChip.type == "NR") {
currentDBM =
"NR dbm = " currentCellInFirstChip.nr.signalNR.dbm.toString();
} else if (currentCellInFirstChip.type == "WCDMA") {
currentDBM = "WCDMA dbm = "
currentCellInFirstChip.wcdma.signalWCDMA.dbm.toString();
print('currentDBM = ' currentDBM);
}
} on PlatformException {
_cellsResponse = null;
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_cellsResponse = cellsResponse;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: _cellsResponse != null
? Center(
child: Text(
'mahmoud = ${currentDBM}n primary = ${_cellsResponse.primaryCellList.length.toString()} n neighbor = ${_cellsResponse.neighboringCellList.length}'),
)
: null,
),
);
}
}
и это класс ответа, исходящий из собственного кода:
import 'models/common/cell_type.dart';
class CellsResponse {
List<CellType> neighboringCellList;
List<CellType> primaryCellList;
CellsResponse({this.neighboringCellList, this.primaryCellList});
CellsResponse.fromJson(Map<String, dynamic> json) {
if (json['neighboringCellList'] != null) {
neighboringCellList = [];
json['neighboringCellList'].forEach((v) {
neighboringCellList.add(new CellType.fromJson(v));
});
}
if (json['primaryCellList'] != null) {
primaryCellList = [];
json['primaryCellList'].forEach((v) {
primaryCellList.add(new CellType.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.neighboringCellList != null) {
data['neighboringCellList'] =
this.neighboringCellList.map((v) => v.toJson()).toList();
}
if (this.primaryCellList != null) {
data['primaryCellList'] =
this.primaryCellList.map((v) => v.toJson()).toList();
}
return data;
}
}
и это плагин класса канала метода:
import 'dart:async';
import 'package:flutter/services.dart';
class CellInfo {
static const MethodChannel _channel = const MethodChannel('cell_info');
static Future<String> get getCellInfo async {
final String version = await _channel.invokeMethod('cell_info');
return version;
}
static const MethodChannel _sim_info = const MethodChannel('sim_info');
static Future<String> get getSIMInfo async {
final String version = await _sim_info.invokeMethod('sim_info');
return version;
}
}
Я хочу создать таймер или что-то подобное, чтобы обновлять эти данные каждые x секунд из плагина самостоятельно.
Комментарии:
1. Вы пробовали использовать
Timer.periodic(Duration(seconds: 1), (Timer t) => initPlatformState())
вinitState
, предполагая вашу проблему, я думаю, это может помочь.2. Или что-то вроде:
Stream.periodic(const Duration(seconds: 1)).take(1).listen((_) => initPlatformState())