Created
February 22, 2022 20:20
-
-
Save craiglabenz/0a67e979ade853ca46ea4db991691366 to your computer and use it in GitHub Desktop.
Demonstrates how use of the wrong BuildContext can yield unexpected results
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
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file | |
// for details. All rights reserved. Use of this source code is governed by a | |
// BSD-style license that can be found in the LICENSE file. | |
import 'package:flutter/material.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: const MyHomePage(title: 'Stale BuildContext demo'), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
final String title; | |
const MyHomePage({ | |
Key? key, | |
required this.title, | |
}) : super(key: key); | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(widget.title), | |
), | |
body: Center( | |
child: Theme( | |
data: ThemeData( | |
textTheme: Theme.of(context).textTheme.copyWith( | |
headline1: const TextStyle(color: Colors.green), | |
), | |
), | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
Builder( | |
// Because this Builder fails to shadow the original `context` variable from | |
// line 37, it allows inner widgets to calculate their position in your app | |
// incorrectly. Remember, a Widget's BuildContext is its associated element in | |
// the ElementTree, so using a different Widget's BuildContext can lead to | |
// extremely tricky bugs. | |
builder: (BuildContext innerContext) => Text( | |
'Green color lost', | |
style: Theme.of(context) | |
.textTheme | |
.headline1! | |
.copyWith(fontWeight: FontWeight.bold), | |
), | |
), | |
Builder( | |
// Because this Builder successfully shadows the original `context` variable from | |
// line 37, it forces inner widgets to correctly calculate their position in your | |
// app. The danger of using an incorrect build context has been diverted! | |
builder: (BuildContext context) => Text( | |
'Green not lost', | |
style: Theme.of(context) | |
.textTheme | |
.headline1! | |
.copyWith(fontWeight: FontWeight.bold), | |
), | |
), | |
], | |
), | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment