102 lines
2.3 KiB
Dart
102 lines
2.3 KiB
Dart
import 'package:flutter/foundation.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter_provider_example/provider.dart';
|
|
import 'package:provider/provider.dart';
|
|
|
|
void main() {
|
|
final provders = [
|
|
ChangeNotifierProvider(
|
|
create: (context) => MyProvider(),
|
|
),
|
|
];
|
|
|
|
runApp(MultiProvider(providers: provders, child: const MyApp()));
|
|
}
|
|
|
|
class MyApp extends StatelessWidget {
|
|
const MyApp({Key? key}) : super(key: key);
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return MaterialApp(
|
|
title: 'Flutter Provider',
|
|
theme: ThemeData(
|
|
primarySwatch: Colors.blue,
|
|
),
|
|
home: const MyHomePage(title: 'Flutter Provier Home Page'),
|
|
);
|
|
}
|
|
}
|
|
|
|
class MyHomePage extends StatefulWidget {
|
|
const MyHomePage({Key? key, required this.title}) : super(key: key);
|
|
final String title;
|
|
|
|
@override
|
|
State<MyHomePage> createState() => _MyHomePageState();
|
|
}
|
|
|
|
class _MyHomePageState extends State<MyHomePage> {
|
|
MyProvider? _provider;
|
|
int _counter = 0;
|
|
|
|
@override
|
|
void initState() {
|
|
if (kDebugMode) {
|
|
print('initState');
|
|
}
|
|
|
|
super.initState();
|
|
|
|
// Load the provider
|
|
_provider = Provider.of<MyProvider>(context, listen: false);
|
|
}
|
|
|
|
@override
|
|
void didChangeDependencies() {
|
|
if (kDebugMode) {
|
|
print('didChangeDependencies');
|
|
}
|
|
super.didChangeDependencies();
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
if (kDebugMode) {
|
|
print("_MyHomePageState.build()");
|
|
}
|
|
|
|
return Scaffold(
|
|
appBar: AppBar(
|
|
title: Text(widget.title),
|
|
),
|
|
body: Center(
|
|
child: ListView.builder(
|
|
itemBuilder: (context, index) {
|
|
final person = _provider!.people[index];
|
|
return ListTile(
|
|
title: Text('Name: ${person.name}'),
|
|
subtitle: Text('Age: ${person.age}'),
|
|
);
|
|
},
|
|
itemCount: _provider?.people.length ?? 0,
|
|
),
|
|
),
|
|
floatingActionButton: FloatingActionButton(
|
|
onPressed: () {
|
|
if (_counter % 2 == 0) {
|
|
_provider!.addPerson(Person('World', 30));
|
|
} else {
|
|
_provider!.removeLastPerson();
|
|
}
|
|
setState(() {
|
|
_counter++;
|
|
});
|
|
},
|
|
tooltip: 'Increment',
|
|
child: const Icon(Icons.add),
|
|
),
|
|
);
|
|
}
|
|
}
|