Skip to content

Instantly share code, notes, and snippets.

@chooyan-eng
Created February 5, 2023 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chooyan-eng/beb971e904bbc38686bd74605312af3b to your computer and use it in GitHub Desktop.
Save chooyan-eng/beb971e904bbc38686bd74605312af3b to your computer and use it in GitHub Desktop.
Example app of rebuilding LayoutBuilder without any setState or state changes.
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
runApp(
const ProviderScope(child: MyApp()),
);
}
final countProvider = StateProvider((ref) => 0);
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(),
body: Column(
children: [
Row(
children: const [
Expanded(
child: Padding(
padding: EdgeInsets.all(16),
child: _DescriptionArea(),
),
),
SizedBox(width: 16),
_ExpandableBar(),
],
),
const SizedBox(height: 32),
const _CountUpButton(),
const SizedBox(height: 32),
const Expanded(child: _Footer()),
],
),
),
);
}
}
class _DescriptionArea extends StatelessWidget {
const _DescriptionArea();
@override
Widget build(BuildContext context) {
return const Text(
'This is a very long text that need multiple lines to be shown.',
style: TextStyle(fontSize: 20),
);
}
}
class _ExpandableBar extends ConsumerWidget {
const _ExpandableBar();
@override
Widget build(BuildContext context, WidgetRef ref) {
final count = ref.watch(countProvider);
return Container(
height: 40,
width: 10.0 * count,
color: Colors.teal,
);
}
}
class _CountUpButton extends ConsumerWidget {
const _CountUpButton();
@override
Widget build(BuildContext context, WidgetRef ref) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 16),
width: double.infinity,
child: ElevatedButton(
onPressed: () {
ref.read(countProvider.notifier).state += 1;
},
child: const Padding(
padding: EdgeInsets.symmetric(vertical: 16),
child: Text('ADD'),
),
),
);
}
}
class _Footer extends StatelessWidget {
const _Footer();
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16),
child: LayoutBuilder(
builder: (context, constraint) {
log('DEBUG: LayoutBuilder built $constraint');
return Text(
'Constraint: $constraint',
style: const TextStyle(
fontSize: 20,
color: Colors.red,
fontWeight: FontWeight.w700,
),
);
},
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment