flutter_safe_async 1.0.1
flutter_safe_async: ^1.0.1 copied to clipboard
Prevents setState called after dispose by safely managing async tasks in Flutter widgets.
example/lib/main.dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_safe_async/flutter_safe_async.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyPage(),
);
}
}
class MyPage extends StatefulWidget {
const MyPage({super.key});
@override
State<MyPage> createState() => MyPageState();
}
class MyPageState extends SafeState<MyPage> {
String status = 'Loading...';
int counter = 0;
int data = 0;
@override
void initState() {
super.initState();
///SAFE ASYNC FUTURE (SafeAsync.run)
SafeAsync.run(
isMounted: () => mountedSafe,
task: () async {
await Future.delayed(const Duration(seconds: 2));
safeSetState(() {
status = 'Loaded successfully';
});
},
);
///SAFE STREAM (auto-cancelled)
final stream = Stream.periodic(
const Duration(seconds: 1),
(count) => count,
);
final subscription = stream.listen((event) {
safeSetState(() {
data = event;
});
});
registerSubscription(subscription);
///SAFE TIMER (auto-cancelled)
final timer = Timer.periodic(const Duration(seconds: 1), (_) {
safeSetState(() {
counter++;
});
});
registerTimer(timer);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('flutter_safe_async Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(status, style: const TextStyle(fontSize: 18)),
const SizedBox(height: 10),
Text('Stream data: $data'),
const SizedBox(height: 10),
Text('Counter: $counter'),
],
),
),
);
}
}