flutter riverpod 状态管理 计数案例

flutter riverpod 状态管理 计数案例_第1张图片
官网
flutter riverpod 状态管理 计数案例_第2张图片
包引用
flutter riverpod 状态管理 计数案例_第3张图片

1 创建监听对象,继承自 StateNotifier,初始状态为0,提供加一 减一方法

class CounterNotifier extends StateNotifier {
  CounterNotifier() : super(0);
  void increment() => state = state + 1;
  void decrement() => state = state - 1;
}

2 创建生产者常量对象,跟着官网写

final counterProvider = StateNotifierProvider.autoDispose(
      (ref) => CounterNotifier(),
);

3 创建消费者组件,继承自ConsumerWidget组件,通过ConsumerWidget组件的watch和read方法获取或者更新状态
flutter riverpod 状态管理 计数案例_第4张图片
4 完整代码

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

void main() {
  runApp(
    const ProviderScope(
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const CounterPage(),
    );
  }
}

class CounterNotifier extends StateNotifier {
  CounterNotifier() : super(0);
  void increment() => state = state + 1;
  void decrement() => state = state - 1;
}

final counterProvider = StateNotifierProvider.autoDispose(
      (ref) => CounterNotifier(),
);

class CounterPage extends ConsumerWidget {
  const CounterPage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context,WidgetRef ref) {
    final counter = ref.watch(counterProvider);
    return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("$counter",style: Theme.of(context).textTheme.headline4)
            ],
          ),
        ),
        persistentFooterButtons:[
          FloatingActionButton(
            onPressed: () {
              ref.read(counterProvider.notifier).increment();
            },
            tooltip: 'Increment',
            child: const Icon(Icons.add),
          ),
          FloatingActionButton(
            onPressed: () {
              ref.read(counterProvider.notifier).decrement();
            },
            tooltip: 'decrement',
            child: const Icon(Icons.minimize),
          )
        ]
    );
  }
}

你可能感兴趣的:(Flutter,flutter)