在dispose()之后如何停止模型?

时间:2019-10-29 12:31:34

标签: flutter dart flutter-layout flutter-provider flutter-widget

我将ProviderChangeNotifier用于UI之外的独立业务逻辑。但是当Model在完成执行功能之前被处置时,我遇到了问题。因为那样,它仍然notifyListeners()并导致错误:

  I /颤振(12044):模型配置的E /颤振(12044):   [错误:flutter / lib / ui / ui_dart_state.cc(148)]未处理的异常:A   处置后使用模型。 E / flutter(12044):一旦有了   在模型上称为dispose(),将无法再使用。

我写了mwe来证明这一点:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Widget1(),
    );
  }
}

class Widget1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: () async {
            await Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => Widget2(),
                ));
          },
        ),
      ),
    );
  }
}


class Widget2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
        builder: (_) => Model(),
        child: Consumer<Model>(builder: (context, model, _) {
          return Scaffold(body: Center(
            child: RaisedButton(
              child: model.success ? Icon(Icons.check) : Icon(Icons.error),
              onPressed: () async {
//              Press back button before Future finish
                await model.init();
              },
            ),
          ));
        }));
  }
}



class Widget3 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(child: Text('Widget 3'));
  }
}


class Model extends ChangeNotifier {
  bool success = false;

  Future<void> init() async {
    await Future.delayed(Duration(seconds: 5));
    success = true;
    notifyListeners();
  }
}

如何连接UI(Widget2Model(例如显示正确的图标)而不会出现此错误?

0 个答案:

没有答案