The first step inpubspec.yaml
Install dependency in
Dependencies: Flutter: SDK: Flutter provider: ^3.0.0+1Copy the code
The second step inlib
Created in theThe provider folder
And the newcount_num_provider.dart
import 'package:flutter/material.dart'; class CountNumProvider with ChangeNotifier { int _num = 0; int get value => _num; // Expose the private variable _num with getincrementNum() { _num++; notifyListeners(); // Update status and inform listeners}}Copy the code
The third step inmain.dart
Registered in the provider
import 'package:provider/provider.dart';
import 'package:flutter_bilibili/provider/count_num_provider.dart';
void main() {
// AMapLocationClient.setApiKey("56383edf209ce13dc3421ea77b7a0e09");
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
returnProviders: [ChangeNotifierProvider(Builder: (_) => CountNumProvider()),], child: MaterialApp( initialRoute:'/',
onGenerateRoute: onGenerateRoute,
title: 'I'm just a decoration.',
debugShowCheckedModeBanner: false, theme: ThemeData(primaryColor: Color(0xffFE9900)), // home: IndexPage() ), ); }}Copy the code
Step 4 Apply to a pageprovider
import 'package:provider/provider.dart';
import 'package:flutter_bilibili/provider/count_num_provider.dart';
class StatePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
var _count = Provider.of<CountNumProvider>(context);
return Scaffold(
body: Center(
child: liveWiget("${_count.value}", _count.incrementNum),
)
);
}
Widget liveWiget(text, cb) {
return Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(text, style: TextStyle(fontSize: 20)),
RaisedButton(
child: Text('increase'), onPressed: cb, ) ], ), ); }}Copy the code