Skip to content

Instantly share code, notes, and snippets.

@Zimins
Last active July 16, 2020 09:16
Show Gist options
  • Save Zimins/a42a569a8e53ecd4a28b8d038391e843 to your computer and use it in GitHub Desktop.
Save Zimins/a42a569a8e53ecd4a28b8d038391e843 to your computer and use it in GitHub Desktop.
Flutter 의 compute 기능을 이용해서 ui blocking을 제거
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
Future<String> longTask() async {
var completer = Completer<String>();
print('requested future');
Future(() async {
print('run future');
// compute를 통해 오래 걸리는 작업의 blocking을 막는다
return await compute(getResult, null);
}).then((value) => completer.complete(value));
print('after await');
return completer.future;
}
// 뭔가 오래 걸리는 작업
static String getResult(String a) {
for (var i = 0; i < 1000000; i++) {}
return "task Done";
}
Widget build(BuildContext context) {
return DefaultTextStyle(
style: Theme.of(context).textTheme.headline2,
textAlign: TextAlign.center,
child: FutureBuilder<String>(
future: longTask(), // a previously-obtained Future<String> or null
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
print("run builder $snapshot");
List<Widget> children;
if (snapshot.hasData) {
print('has data');
children = <Widget>[
Icon(
Icons.check_circle_outline,
color: Colors.green,
size: 60,
),
Padding(
padding: const EdgeInsets.only(top: 16),
child: Text('Result: ${snapshot.data}'),
)
];
} else if (snapshot.hasError) {
print('has error');
children = <Widget>[
Icon(
Icons.error_outline,
color: Colors.red,
size: 60,
),
Padding(
padding: const EdgeInsets.only(top: 16),
child: Text('Error: ${snapshot.error}'),
)
];
} else {
print('no data');
children = <Widget>[
SizedBox(
child: CircularProgressIndicator(),
width: 60,
height: 60,
),
const Padding(
padding: EdgeInsets.only(top: 16),
child: Text(
'Awaiting result...',
style: TextStyle(color: Colors.white),
),
)
];
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: children,
),
);
},
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment