我用 ChangeNotifier Provider 创建的计数器将其值复制到其他计数器实例

My Counter made with ChangeNotifier Provider replicates its value with other Counter Instances

我正在为购物车创建一个计数器。问题是当一个计数器的值发生变化时,它会影响屏幕上的所有其他计数器。我使用了 ChangeNotifier,但我不知道自己做错了什么。

这是计数器模型

import 'package:flutter/material.dart';

class CounterModel extends ChangeNotifier {
  int _count = 0;
  int get getCount => _count;

  void increment() {
    if (_count >= 0) {
      _count++;
    }
    notifyListeners();
  }

  void decrease() {
    if (_count > 0) {
      _count--;
    }
    notifyListeners();
  }
}

这是计数器的构建

import 'package:flutter/material.dart';
import 'package:provide_count/counter_model.dart';
import 'package:provider/provider.dart';

class ProvideCount extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final counter = Provider.of<CounterModel>(context);
    return Row(
      children: <Widget>[
        IconButton(icon: Icon(Icons.add), onPressed: counter.increment),
        Text('${counter.getCount}'),
        IconButton(icon: Icon(Icons.remove), onPressed: counter.decrease),
      ],
    );
  }
}

这是 main.dart 文件

import 'package:flutter/material.dart';
import 'package:provide_count/counter_model.dart';
import 'package:provide_count/providecount.dart';
import 'package:provider/provider.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<CounterModel>(create: (_) => CounterModel()),
      ],
      child: MaterialApp(
        title: 'Flutter Demo',
        home: SafeArea(
          top: true,
          child: Scaffold(
            body: Column(
              children: [
                ProvideCount(),
                ProvideCount(),
                ProvideCount(),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

问题是你的树的顶部有一个 ChangeNotifierProvider

当您调用 Provider.of<CounterModel> 时,您正在搜索树上最近的 Provider 小部件,这对所有小部件都是相同的。所以他们同步了。

如果您不希望这种情况发生,您可以停止使用 Provider,或者您至少可以将每个 ProvideCount 换成它们自己的 Provider:

return MaterialApp(
      title: 'Flutter Demo',
      home: SafeArea(
        top: true,
        child: Scaffold(
          body: Column(
            children: [
              ChangeNotifierProvider<CounterModel>(
                create: (_) => CounterModel()
                child: ProvideCount(),
              ),
              ChangeNotifierProvider<CounterModel>(
                create: (_) => CounterModel()
                child: ProvideCount(),
              ),
              ChangeNotifierProvider<CounterModel>(
                create: (_) => CounterModel()
                child: ProvideCount(),
              ),
            ],
          ),
        ),
      ),
    );