global_state 1.0.1 copy "global_state: ^1.0.1" to clipboard
global_state: ^1.0.1 copied to clipboard

Global State automatically rebuilds Widgets on value changes. Includes an api for creating transition values to produce controllable animations.

example/example.dart

import 'package:flutter/material.dart';
import 'package:global_state/gs.dart';
import 'package:http/http.dart' as http;

void main() {
  fetchAndUpdateImage();
  runApp(MaterialApp(title: 'Fetch image', home: ImageDisplay()));
}

// GS values storage.
class GlobalState {
  static Widget get image => gs['image'];
  static set image(Widget widget) => gs['image'] = widget;
}

class ImageDisplay extends StatelessWidget with GS {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GlobalState.image == null
          ? Center(
              child: Text(
                'Loading...',
                textScaleFactor: 2,
              ),
            )
          : Align(
              alignment: Alignment(0, transition(2000, delayMillis: 800) - 1),
              child: GlobalState.image),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.refresh),
        onPressed: () async {
          GlobalState.image = null;
          await fetchAndUpdateImage();
          // Restarting context transitions after the new image has loaded
          // causes the new image to also transition from top to center.
          TransitionGroup(context: context).restart();
        },
      ),
    );
  }
}

class TransitionImage extends StatelessWidgetGS {
  final Image image;
  const TransitionImage(this.image);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Opacity(opacity: transition(1500), child: image),
      onTap: () async {
        if (await fetchAndUpdateImage()) {
          TransitionGroup(context: context).restart();
        }
      },
    );
  }
}

bool _fetching = false;

Future<bool> fetchAndUpdateImage(
    [String url = 'https://picsum.photos/300/200']) async {
  if (_fetching) {
    return false;
  }
  try {
    _fetching = true; // locks the fetching function
    final response = await http.get(url);
    GlobalState.image = TransitionImage(Image.memory(response.bodyBytes));
    return true;
  } finally {
    _fetching = false;
  }
}
2
likes
40
points
17
downloads

Publisher

unverified uploader

Weekly Downloads

Global State automatically rebuilds Widgets on value changes. Includes an api for creating transition values to produce controllable animations.

Homepage

License

MIT (license)

Dependencies

flutter

More

Packages that depend on global_state