大神链接
import 'package:flutter/foundation.dart';
class CounterNotifier with ChangeNotifier {
int _count = 0;
// get 方法
int get count => _count;
increment() {
_count++;
notifyListeners();
}
}
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:provider_demo/notifier.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider.value(
value: CounterNotifier(),
child: MaterialApp(
home: ProvidePage(title: "Provider Demo",),
),
);
}
}
class ProvidePage extends StatelessWidget {
final String title;
ProvidePage({this.title});
@override
Widget build(BuildContext context) {
// 获取 CounterNotifier 数据
final counter = Provider.of<CounterNotifier>(context);
return Scaffold(
appBar: AppBar(
title: Text(this.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("点击次数:"),
Text("${counter.count}",style: Theme.of(context).textTheme.display1,),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: (){
counter.increment();
},
tooltip: "增加",
child: Icon(Icons.add),
),
);
}
}