Last active
October 12, 2022 17:50
-
-
Save cliftonlabrum/ba3536fade3045af15addd498ccdd5eb to your computer and use it in GitHub Desktop.
Provider Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:provider/provider.dart'; | |
import "dart:math"; | |
void main() { | |
runApp( | |
MultiProvider( | |
providers: [ | |
ChangeNotifierProvider(create: (context) => Person()), | |
], | |
child: const MyApp(), | |
), | |
); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
//::: | |
var provider = Provider.of<Person>(context); | |
//::: | |
return MaterialApp( | |
title: 'Provider Demo', | |
home: Scaffold( | |
appBar: AppBar( | |
title: const Text('Provider'), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
TextButton( | |
onPressed: () { | |
provider.addStar(); | |
}, | |
child: const Text('Add Star'), | |
), | |
Text( | |
'⭐️ ${provider.stars}', | |
), | |
const Divider(), | |
TextButton( | |
onPressed: () { | |
provider.addPet(); | |
}, | |
child: const Text('Add Pet'), | |
), | |
for (var pet in provider.pets) Text(pet) | |
], | |
), | |
), | |
), | |
); | |
} | |
} | |
class Person with ChangeNotifier { | |
int stars = 0; | |
List<String> pets = []; | |
Person(); | |
addStar() { | |
stars++; | |
notifyListeners(); | |
} | |
addPet() { | |
var list = ['cat', 'dog', 'hamster', 'fish', 'bird']; | |
//Get random list element | |
final random = Random(); | |
var element = list[random.nextInt(list.length)]; | |
pets.add(element); | |
notifyListeners(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment