shared_app_data.0.dart 2.42 KB
Newer Older
1 2 3 4
// 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.

5
/// Flutter code sample for [SharedAppData].
6 7 8 9

import 'package:flutter/material.dart';

class ShowSharedValue extends StatelessWidget {
10
  const ShowSharedValue({ super.key, required this.appDataKey });
11 12 13 14 15

  final String appDataKey;

  @override
  Widget build(BuildContext context) {
16 17
    // The SharedAppData.getValue() call causes this widget to depend on the
    // value of the SharedAppData's 'foo' key. If it's changed, with
18 19 20 21 22 23
    // SharedAppData.setValue(), then this widget will be rebuilt.
    final String value = SharedAppData.getValue<String, String>(context, appDataKey, () => 'initial');
    return Text('$appDataKey: $value');
  }
}

24 25
// Demonstrates that changes to the SharedAppData _only_ cause the dependent
// widgets to be rebuilt. In this case that's the ShowSharedValue widget that's
26 27
// displaying the value of a key whose value has been updated.
class Home extends StatefulWidget {
28
  const Home({ super.key });
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int _fooVersion = 0;
  int _barVersion = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            const ShowSharedValue(appDataKey: 'foo'),
            const SizedBox(height: 16),
            const ShowSharedValue(appDataKey: 'bar'),
            const SizedBox(height: 16),
            ElevatedButton(
              child: const Text('change foo'),
              onPressed: () {
                _fooVersion += 1;
53 54
                // Changing the SharedAppData's value for 'foo' causes the
                // widgets that depend on 'foo' to be rebuilt.
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
                SharedAppData.setValue<String, String?>(context, 'foo', 'FOO $_fooVersion'); // note: no setState()
              },
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              child: const Text('change bar'),
              onPressed: () {
                _barVersion += 1;
                SharedAppData.setValue<String, String?>(context, 'bar', 'BAR $_barVersion');  // note: no setState()
              },
            ),
          ],
        ),
      ),
    );
  }
}

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