flutter 状态管理之 provider

21 min read

插件地址

https://pub.dev/packages/provider#-installing-tab-

import 'package:flutter/material.dart';
import 'package:flutter_navigator_v2/counter.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: CountModel(),
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: const FirstPage(),
      ),
    );
  }
}

class FirstPage extends StatelessWidget {
  const FirstPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final _counter = Provider.of<CountModel>(context);

    return Scaffold(
      appBar: AppBar(title: Text('first page')),
      body: Center(
        child: Text('first page count=${_counter.counter}'),
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.polymer),
        onPressed: () => Navigator.of(context)
            .push(MaterialPageRoute(builder: (context) => SecondPage())),
      ),
    );
  }
}

class SecondPage extends StatelessWidget {
  const SecondPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final _counter = Provider.of<CountModel>(context);
    return Scaffold(
      appBar: AppBar(title: Text('second page')),
      body: const Center(
        child: Text('Second page count='),
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () => _counter.increment(),
      ),
    );
  }
}