Обновите первую модель в ChangeNotifierProxyProvider, зависимая модель не меняется - PullRequest
0 голосов
/ 29 мая 2020

пробовал этот ChangeNotifierProxyProvider, Auth - это модель, от которой зависит Infosource,

ChangeNotifierProxyProvider<Auth, InfoSource>

Насколько я понимаю, если я обновлю Auth, будет вызвана следующая строка, но не так:

  update: (BuildContext context, Auth value, InfoSource previous) {
          previous.updateAuth(value);
          return previous;
        },

я сделал следующее: если я нажму кнопку «Поднять», я обновлю имя Auth, но информационный источник не обновится, любая помощь будет принята с благодарностью:

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

void main2() => runApp(MyApp());

void main() => runApp(MultiProvider(providers: [
      Provider<User>(
        create: (_) {
          return User('Flutta');
        },
        lazy: false,
      ),
      ProxyProvider<User, Auth>(
        update: (BuildContext context, User value, Auth previous) {
          return Auth(value);
        },
      ),
      ChangeNotifierProxyProvider<Auth, InfoSource>(
        create: (BuildContext context) {
          return InfoSource();
        },
        update: (BuildContext context, Auth value, InfoSource previous) {
          previous.updateAuth(value);
          return previous;
        },
      ),
    ], child: MyApp()));

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Sample());
  }
}

class Sample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('sample')),
      body: mybody(context),
    );
  }

  Widget mybody(context) {
    return Column(
      children: <Widget>[
        RaisedButton(
          onPressed: () {
            print("Button Pressed");
            var a = Provider.of<Auth>(context, listen: false);
            a.updateName('Flutter');
          },
          child: Text("Press here"),
        ),
        Text(Provider.of<Auth>(context, listen: false).currentName()),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(Provider.of<InfoSource>(context).news()),
        )
      ],
    );
  }
}

class User {
  String name;
  User(this.name);
}

class Auth  {
  final user;

  Auth(this.user);

  String currentName() {
    return user.name;
  }

  updateName(String _name) {
    user.name = _name;
  }
}

class InfoSource extends ChangeNotifier {
  Auth auth;

  InfoSource();

  String news() {
    return auth.currentName() + ' is in the news';
  }

  updateAuth(Auth _auth) {
    print('update auth');
    this.auth = _auth;
  }

  updateNews() {
    notifyListeners();
  }
}
...