Flutter Advanced Topics
The basics get an application on screen. This page is about the three things that separate a working application from a good one: state that stays coherent as the app grows, motion that explains what just happened, and widgets that draw something the framework does not provide out of the box.
Beyond Provider and Riverpod, two patterns are worth knowing because they scale differently.
ChangeNotifier with Repositories
Separate where the data comes from from where the data is displayed. A repository owns the data and the network calls; a notifier wraps a repository and exposes the state to the widget tree.
class ProductRepository {
ProductRepository(this._client);
final ApiClient _client;
Future<List<Product>> fetchAll() async {
final response = await _client.get('/products');
return (response as List).map((json) => Product.fromJson(json)).toList();
}
}
class ProductListNotifier extends ChangeNotifier {
ProductListNotifier(this._repository);
final ProductRepository _repository;
List<Product> _products = [];
bool _loading = false;
String? _error;
Future<void> load() async {
_loading = true;
_error = null;
notifyListeners();
try {
_products = await _repository.fetchAll();
} catch (e) {
_error = e.toString();
} finally {
_loading = false;
notifyListeners();
}
}
}
This keeps the widget layer free of try/catch and of HTTP details, and it makes the notifier trivial to test with a fake repository.
Bloc and Cubit
Bloc makes the flow of data explicit as a stream of states. A Cubit is the simpler form: methods emit new states directly, without events.
class CounterCubit extends Cubit<int> {
CounterCubit() : super(0);
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
}
The advantage is that every state change is a single, traceable emission, which makes logs, time-travel debugging, and testing straightforward. The cost is more ceremony for small features.
Flutter’s animation system is built on Animation, an abstract description of a value over time, and AnimationController, which drives it.
Implicit Animations
The quickest way to animate is to let a widget animate a property change on its own.
AnimatedContainer(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
width: _expanded ? 200 : 100,
height: _expanded ? 200 : 100,
color: _expanded ? Colors.blue : Colors.grey,
)
AnimatedOpacity, AnimatedPositioned, AnimatedAlign, and AnimatedCrossFade work the same way.
Explicit Animations
When you need to control the timing, use a controller and a Tween.
class FadeIn extends StatefulWidget {
const FadeIn({super.key, required this.child});
final Widget child;
@override
State<FadeIn> createState() => _FadeInState();
}
class _FadeInState extends State<FadeIn> with SingleTickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 400),
);
late final Animation<double> _opacity =
Tween<double>(begin: 0, end: 1).animate(_controller);
@override
void initState() {
super.initState();
_controller.forward();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FadeTransition(opacity: _opacity, child: widget.child);
}
}
Two rules save a lot of pain: call dispose() on the controller, and drive it with vsync: this so it does not tick when the screen is off.
Hero animations let a widget fly from one route to another - the standard shared-element transition between a list and a detail screen.
Hero(
tag: 'product-${product.id}',
child: Image.network(product.imageUrl),
)
When the framework has no widget for what you need, you can write one - and often the simplest thing to write is a CustomPainter.
class SparklinePainter extends CustomPainter {
SparklinePainter(this.values);
final List<double> values;
@override
void paint(Canvas canvas, Size size) {
final path = Path();
final step = size.width / (values.length - 1);
for (var i = 0; i < values.length; i++) {
final x = i * step;
final y = size.height - (values[i] * size.height);
if (i == 0) {
path.moveTo(x, y);
} else {
path.lineTo(x, y);
}
}
canvas.drawPath(
path,
Paint()
..color = const Color(0xFF2F6FED)
..style = PaintingStyle.stroke
..strokeWidth = 2,
);
}
@override
bool shouldRepaint(SparklinePainter oldDelegate) =>
oldDelegate.values != values;
}
Used from a widget:
CustomPaint(
size: const Size(double.infinity, 60),
painter: SparklinePainter(values),
)
shouldRepaint decides whether the layer needs to be repainted; return true only when something that affects the drawing has actually changed.
For a widget that is a composition rather than a drawing, write a widget that takes a builder callback - the same shape Flutter uses for Container, Padding, and Center.
class SectionCard extends StatelessWidget {
const SectionCard({super.key, required this.builder});
final WidgetBuilder builder;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: Theme.of(context).colorScheme.surfaceContainerHighest,
),
child: builder(context),
);
}
}
Performance work in Flutter is mostly about rebuilding less.
- Make constructors
constwherever possible. - Give long lists keys (
ListView.builderwith akeyon each item) so the framework can match elements across rebuilds. - Use
constwidgets inbuildso identical subtrees are skipped. - Use
RepaintBoundaryaround subtrees that repaint independently. - Check the profile with
flutter run --profileand the DevTools timeline, not by intuition. - Keep expensive work out of
build; compute it once and cache it.
Approach: The question spans animation and rendering, so answer it in the order the framework executes: the controller produces a value over time, the Animation maps that value onto a property, the AnimationBuilder or AnimatedWidget applies it to the tree, and only then does the framework decide what to repaint.
Steps:
- An
AnimationControllerneeds avsync; passingthisfrom aStatemixed withTickerProviderStateMixinties its ticks to that state’s lifecycle, so it stops when the screen is not visible. - The controller’s
valueruns from 0.0 to 1.0 over the duration. ATweenmaps that progress onto the property you actually want - opacity, a size, a colour - andanimateproduces anAnimationthat can be driven by the controller. AnimatedBuilderorFadeTransitionrebuilds only the subtree that depends on thatAnimation, rather than the whole page, which is why explicit animations are cheaper than rebuilding the parent insetState.- The controller must be disposed in
dispose(), otherwise it keeps a ticker alive and leaks. - For the repaint question,
CustomPainter.shouldRepaintis the gate: returningtrueunconditionally repaints on every frame; comparing the new data with the old one lets unchanged layers be reused.
Answer: The controller drives progress from 0 to 1 over the duration, the Tween maps that progress onto the target property, AnimatedBuilder applies it to the smallest possible subtree, the controller is disposed with the state, and shouldRepaint decides per frame whether the layer has to be redrawn.
The course root page gathers the whole path together and walks through deployment - signing the build, producing the artefacts each store expects, and the checklist to run before you submit.
