Created
January 29, 2020 22:19
-
-
Save luigi-rosso/0e3ed273e52764bf1d7bdacca49cccd2 to your computer and use it in GitHub Desktop.
Flutter Frame Rate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter/scheduler.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatefulWidget { | |
@override | |
_MyAppState createState() => _MyAppState(); | |
} | |
class _MyAppState extends State<MyApp> { | |
@override | |
void initState() { | |
SchedulerBinding.instance.addPersistentFrameCallback(_frame); | |
super.initState(); | |
} | |
int _lastFrameTime = 0; | |
String _frameRate = "0 fps"; | |
void _frame(Duration elapsed) { | |
int elapsedMicroseconds = elapsed.inMicroseconds; | |
double elapsedSeconds = (elapsedMicroseconds - _lastFrameTime) * 1e-6; | |
if (elapsedSeconds != 0) { | |
_lastFrameTime = elapsedMicroseconds; | |
setState(() { | |
_frameRate = '${(1.0 / elapsedSeconds).round()} fps'; | |
}); | |
} | |
// Redraw. | |
SchedulerBinding.instance.scheduleFrame(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: Material( | |
child: Container( | |
child: Center( | |
child: Text(_frameRate), | |
), | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment