inherited_theme.0.dart 2.13 KB
Newer Older
1 2 3 4 5 6
// Copyright 2014 The Flutter Authors. 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';

7 8
/// Flutter code sample for [InheritedTheme].

9
void main() {
10
  runApp(const InheritedThemeExampleApp());
11 12 13
}

class MyAppBody extends StatelessWidget {
14
  const MyAppBody({super.key});
15 16 17 18 19 20 21 22 23 24 25

  @override
  Widget build(BuildContext context) {
    final NavigatorState navigator = Navigator.of(context);
    // This InheritedTheme.capture() saves references to themes that are
    // found above the context provided to this widget's build method
    // excluding themes are found above the navigator. Those themes do
    // not have to be captured, because they will already be visible from
    // the new route pushed onto said navigator.
    // Themes are captured outside of the route's builder because when the
    // builder executes, the context may not be valid anymore.
26
    final CapturedThemes themes = InheritedTheme.capture(from: context, to: navigator.context);
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
    return GestureDetector(
      onTap: () {
        Navigator.of(context).push(
          MaterialPageRoute<void>(
            builder: (BuildContext _) {
              // Wrap the actual child of the route in the previously
              // captured themes.
              return themes.wrap(
                Container(
                  alignment: Alignment.center,
                  color: Colors.white,
                  child: const Text('Hello World'),
                ),
              );
            },
          ),
        );
      },
      child: const Center(child: Text('Tap Here')),
    );
  }
}

50 51
class InheritedThemeExampleApp extends StatelessWidget {
  const InheritedThemeExampleApp({super.key});
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        // Override the DefaultTextStyle defined by the Scaffold.
        // Descendant widgets will inherit this big blue text style.
        body: DefaultTextStyle(
          style: TextStyle(fontSize: 48, color: Colors.blue),
          child: MyAppBody(),
        ),
      ),
    );
  }
}