Last active
May 12, 2023 09:21
-
-
Save PlugFox/4f16190f14f5760b69b88952a63c93b2 to your computer and use it in GitHub Desktop.
Container pitfall
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
/* | |
* Container pitfall | |
* https://gist.github.com/PlugFox/4f16190f14f5760b69b88952a63c93b2 | |
* https://dartpad.dev/4f16190f14f5760b69b88952a63c93b2 | |
* Matiunin Mikhail <plugfox@gmail.com>, 12 May 2023 | |
*/ | |
// ignore_for_file: avoid_print | |
import 'dart:async'; | |
import 'package:flutter/material.dart'; | |
void main() => runZonedGuarded<Future<void>>( | |
() async => runApp(const App()), | |
(error, stackTrace) => print('Top level exception $error'), | |
); | |
class App extends StatefulWidget { | |
const App({super.key}); | |
@override | |
State<App> createState() => _AppState(); | |
} | |
class _AppState extends State<App> { | |
bool $error = false; | |
@override | |
Widget build(BuildContext context) => MaterialApp( | |
title: 'Container pitfall', | |
home: Scaffold( | |
appBar: AppBar( | |
title: const Text('Container pitfall'), | |
), | |
body: SafeArea( | |
child: Center( | |
child: StatefulBuilder( | |
builder: (context, setState) => Column( | |
mainAxisSize: MainAxisSize.min, | |
crossAxisAlignment: CrossAxisAlignment.center, | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
Container( | |
color: $error ? Colors.red : null, // <-- Pitfall | |
child: const MyForm(), | |
), | |
const Divider(), | |
ElevatedButton( | |
child: const Text('Switch color'), | |
onPressed: () => setState(() => $error = !$error), | |
), | |
], | |
), | |
), | |
), | |
), | |
), | |
); | |
} | |
class MyForm extends StatefulWidget { | |
const MyForm({super.key}); | |
@override | |
State<MyForm> createState() => _MyFormState(); | |
} | |
class _MyFormState extends State<MyForm> { | |
@override | |
void initState() { | |
super.initState(); | |
print('initState'); | |
/* E.g. http request */ | |
} | |
@override | |
void dispose() { | |
print('dispose'); | |
super.dispose(); | |
} | |
@override | |
Widget build(BuildContext context) => const SizedBox.square( | |
dimension: 128, | |
child: Placeholder(), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment