shared_app_data.1.dart 1.97 KB
Newer Older
1 2 3 4 5 6 7
// 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/foundation.dart';
import 'package:flutter/material.dart';

8 9
/// Flutter code sample for [SharedAppData].

10 11 12 13
// A single lazily-constructed object that's shared with the entire application
// via `SharedObject.of(context)`. The value of the object can be changed with
// `SharedObject.reset(context)`. Resetting the value will cause all of the
// widgets that depend on it to be rebuilt.
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
class SharedObject {
  SharedObject._();

  static final Object _sharedObjectKey = Object();

  @override
  String toString() => describeIdentity(this);

  static void reset(BuildContext context) {
    // Calling SharedAppData.setValue() causes dependent widgets to be rebuilt.
    SharedAppData.setValue<Object, SharedObject>(context, _sharedObjectKey, SharedObject._());
  }

  static SharedObject of(BuildContext context) {
    // If a value for _sharedObjectKey has never been set then the third
    // callback parameter is used to generate an initial value.
    return SharedAppData.getValue<Object, SharedObject>(context, _sharedObjectKey, () => SharedObject._());
  }
}

34 35
// An example of a widget which depends on the SharedObject's value, which might
// be provided - along with SharedObject - in a Dart package.
36
class CustomWidget extends StatelessWidget {
37
  const CustomWidget({super.key});
38 39 40 41 42 43 44 45 46 47 48 49 50 51

  @override
  Widget build(BuildContext context) {
    // Will be rebuilt if the shared object's value is changed.
    return ElevatedButton(
      child: Text('Replace ${SharedObject.of(context)}'),
      onPressed: () {
        SharedObject.reset(context);
      },
    );
  }
}

class Home extends StatelessWidget {
52
  const Home({super.key});
53 54 55 56

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
57
      body: Center(child: CustomWidget()),
58 59 60 61 62 63 64
    );
  }
}

void main() {
  runApp(const MaterialApp(home: Home()));
}