Skip to content

Instantly share code, notes, and snippets.

@musoftware
Created March 13, 2022 22:14
Show Gist options
  • Save musoftware/f469dd18394ddf8bdd018537e6c5265c to your computer and use it in GitHub Desktop.
Save musoftware/f469dd18394ddf8bdd018537e6c5265c to your computer and use it in GitHub Desktop.
Simple Provider Flutter Example
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (_) => Person(name: "Yohan", age: 25),
child: MyApp(),
),
);
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyBody(),
);
}
}
class MyBody extends StatefulWidget {
const MyBody({Key? key}) : super(key: key);
@override
State<MyBody> createState() => _MyBodyState();
}
class _MyBodyState extends State<MyBody> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
Center(
child: Consumer<Person>(
builder: (context, value, child) {
return Text(value.name);
},
),
),
ElevatedButton(
child: Text('Change'),
onPressed: () {
Provider.of<Person>(context, listen: false).Change();
},
)
],
)));
}
}
class Person extends ChangeNotifier {
var name = "test";
Person({name, age}) {
this.name = name;
}
void Change() {
this.name = 'Mahmoud';
notifyListeners();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment