Closed easyterm-devel closed 4 years ago
full example:
import 'dart:async';
import 'package:flutter/material.dart';
import 'dart:isolate';
import 'package:flutter/services.dart';
import 'package:wifi_iot/wifi_iot.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
.then((_) {
runApp(new MyApp());
});
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Isolate Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Isolates'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Isolate _isolate;
bool _running = false;
static int _counter = 0;
String notification = "";
ReceivePort _receivePort;
void _start() async {
_running = true;
_receivePort = ReceivePort();
_isolate = await Isolate.spawn(_scanAP, _receivePort.sendPort);
_receivePort.listen(_handleMessage, onDone:() {
print("done!");
});
}
static void _scanAP(SendPort sendPort) async {
Timer.periodic(new Duration(seconds: 5), (Timer t) async {
List<WifiNetwork> scanResult;
try {
scanResult = await WiFiForIoTPlugin.loadWifiList();
//sendPort.send(scanResult.toString());
} on PlatformException {
scanResult = List<WifiNetwork>();
}
_counter++;
// String msg = 'notification ' + _counter.toString() + scanResult.toString();
// print('SEND: ' + msg);
// sendPort.send(msg);
});
}
void _handleMessage(dynamic data) {
print('RECEIVED: ' + data);
setState(() {
notification = data;
});
}
void _stop() {
if (_isolate != null) {
setState(() {
_running = false;
notification = '';
});
_receivePort.close();
_isolate.kill(priority: Isolate.immediate);
_isolate = null;
}
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
notification,
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _running ? _stop : _start,
tooltip: _running ? 'Timer stop' : 'Timer start',
child: _running ? new Icon(Icons.stop) : new Icon(Icons.play_arrow),
),
);
}
}
Future<List<WifiNetwork>> loadWifiList() async {
List<WifiNetwork> htResultNetwork;
try {
htResultNetwork = await WiFiForIoTPlugin.loadWifiList();
} on PlatformException {
htResultNetwork = List<WifiNetwork>();
}
return htResultNetwork;
}
Probably I forgot think about initializing part:
@override
initState() {
super.initState();
WiFiForIoTPlugin.setEnabled(true);
}
but with apply method above not resolved too..
Platform APIs have to be called from main Isolate.
Based on skeleton: https://gist.github.com/jebright/a7086adc305615aa3a655c6d8bd90264
another approach not working properly: