Skip to content

Instantly share code, notes, and snippets.

@jtlapp
Created September 11, 2019 04:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtlapp/4eb3f47d3806c144c5a172933fe6c1f4 to your computer and use it in GitHub Desktop.
Save jtlapp/4eb3f47d3806c144c5a172933fe6c1f4 to your computer and use it in GitHub Desktop.
Flutter Provider sharing static state
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
// Provider with unchanging state
class User {
User(this.name);
final String name;
}
var currentUser = User("Frodo Baggins");
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Provider<User>.value(
value: currentUser,
child: Scaffold(
appBar: AppBar(
title: Consumer<User>(
builder: (context, user, child) =>
Text("Page for ${user.name}"),
),
),
body: MyWidget(),
),
);
}
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Consumer<User>(
builder: (context, user, child) => Text(
'User: ${user.name}',
style: Theme.of(context).textTheme.display1,
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment