Reputation: 1983
What is the difference btw the two of them (sleep vs Future.delayed)? What's going on behind the scenes in both scenarios?
I don't understand the different outcomes in the following examples.
Future.delayed: does what I'd expect it to do:
import 'package:flutter/material.dart';
import 'dart:io';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Color appColor = Colors.green;
changeColors() async {
setState(() {
appColor = Color(0xff000000);
});
await Future.delayed(Duration(seconds: 10));
print('after 10 seconds');
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Center(
child: Column(
children: [
Container(height: 100, width: 100, color: appColor),
FlatButton(
onPressed: () => changeColors(),
child: Text('click me'),
),
],
),
),
),
),
);
}
}
sleep: does NOT do what I'd expect it to do:
import 'package:flutter/material.dart';
import 'dart:io';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Color appColor = Colors.green;
changeColors() {
setState(() {
appColor = Color(0xff000000);
});
sleep(Duration(seconds:10));
print('after 10 seconds');
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Center(
child: Column(
children: [
Container(height: 100, width: 100, color: appColor),
FlatButton(
onPressed: () => changeColors(),
child: Text('click me'),
),
],
),
),
),
),
);
}
}
Upvotes: 0
Views: 1032