我试图在Flutter应用程序(Flutter版本1.12.13 + hotfix8)中实现MVP模式。
我的 Controller (演示者)是一个单例,如下所示:

import 'package:flutter/material.dart';

// local file imports
import 'package:prototype/gui/screens/welcome/welcome.dart';

// this is a singleton
class Controller  {
  static final Controller _instance = Controller._internal();
  Widget _currentWidget;

  Controller._internal() {
    this._currentWidget = ScreenWelcome();
  }

  factory Controller() => _instance;

  Widget get currentWidget => this._currentWidget;

  set currentWidget(Widget widget){
    _currentWidget = widget;
  }
}

我的主屏幕如下所示:

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

// local file imports
import 'package:prototype/controller/conroller.dart';
import 'package:prototype/gui/screens/register/register.dart';
import 'package:prototype/gui/screens/register/sign_in.dart';
import 'package:prototype/gui/screens/text_viewer/text_viewer.dart';

class ScreenWelcome extends StatelessWidget {
  final _controller = Controller();

  @override
  Widget build(BuildContext context) {
    return Container(
      child: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Image.asset('resources/zombiepaar.jpg',
                width: 500, height: 500, fit: BoxFit.fitWidth),
            SizedBox(
              height: 20.0,
            ),
            RaisedButton(
              child: Text("Ein neues Konto erstellen"),
              onPressed: () => _controller.currentWidget = ScreenRegister(),
            ),
            SizedBox(
              height: 20.0,
            ),
            RaisedButton(
              child: Text("Mit bestehendem Konto einloggen"),
              onPressed: () => _controller.currentWidget = ScreenSignIn(),
            ),
            SizedBox(
              height: 20.0,
            ),
            Row(
              children: <Widget>[
                GestureDetector(
                  child: Text(
                    "Nutzungsbedingungen",
                    style: TextStyle(
                        decoration: TextDecoration.underline,
                        color: Colors.blue),
                  ),
                  onTap: () => Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => ScreenTextViewer(
                            title: "Nutzungsbedingungen",
                            ressourceFileToLoad: 'resources/AGBs.txt'),
                      )),
                ),
                SizedBox(
                  width: 20.0,
                ),
                GestureDetector(
                  child: Text(
                    "Datenschutzrichtlinien",
                    style: TextStyle(
                        decoration: TextDecoration.underline,
                        color: Colors.blue),
                  ),
                  onTap: () => Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => ScreenTextViewer(
                          title: "Nutzungsbedingungen",
                          ressourceFileToLoad: 'resources/AGBs.txt'),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}


但是,当我运行我的应用程序时,出现以下运行时错误:
D/FlutterActivityAndFragmentDelegate(21372): Executing Dart entrypoint: main, and sending initial route: /
E/flutter (21372): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Reading static variable '_instance@545324594' during its initialization
E/flutter (21372): #0      Controller._instance (package:prototype/controller/conroller.dart:9:27)
E/flutter (21372): #1      new Controller (package:prototype/controller/conroller.dart:17:27)
E/flutter (21372): #2      new ScreenWelcome (package:prototype/gui/screens/welcome/welcome.dart:11:23)
E/flutter (21372): #3      new Controller._internal (package:prototype/controller/conroller.dart:14:27)
E/flutter (21372): #4      Controller._instance (package:prototype/controller/conroller.dart:9:50)
E/flutter (21372): #5      Controller._instance (package:prototype/controller/conroller.dart:9:27)
E/flutter (21372): #6      new Controller (package:prototype/controller/conroller.dart:17:27)
E/flutter (21372): #7      new MyApp (package:prototype/main.dart:10:22)
E/flutter (21372): #8      main (package:prototype/main.dart:6:23)
E/flutter (21372): #9      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:239:25)
E/flutter (21372): #10     _rootRun (dart:async/zone.dart:1126:13)
E/flutter (21372): #11     _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter (21372): #12     _runZoned (dart:async/zone.dart:1518:10)
E/flutter (21372): #13     runZoned (dart:async/zone.dart:1502:12)
E/flutter (21372): #14     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:231:5)
E/flutter (21372): #15     _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:307:19)
E/flutter (21372): #16     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12)

任何想法如何解决这个问题?我发现Google没什么帮助,而且对dart和Flutter来说还很陌生。也许我以错误的方式实现了单例类(class)?

编辑:Mi main.dart文件是

import 'package:flutter/material.dart';

// local file imports
import 'package:prototype/controller/conroller.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of the application.
  final controller = Controller(); // presenter in MVP design pattern

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'MyApp',
      home: controller.currentWidget, // controller decides the main widget
    );
  }
}


最佳答案

您具有循环依赖性。创建ScreenWelcome会调用Controller构造函数,该构造函数读取_instance字段,该字段会构造Controller,并创建一个ScreenWelcome。您很幸运_instance字段是惰性的,因为它随后可以较早地检测到周期,而不是导致堆栈溢出。

如果您有两个带有最终字段的类,那么它们必须彼此指向。这基本上是不可能的。幸运的是_currentWidget并不是最终的,因此这是在创建两个对象之后需要设置的。

我会做类似的事情:

class Controller {
  static final _instance = Controller._();
  Widget_currentWidget;
  factory Controller() => _instance;
  Controller._();
}
class ScreenWelcome {
  final Controller _controller;
  ScreenWelcome() : _controller = Controller() {
    // This is the soonest a reference to this widget is available.
    _controller.currentWidget = this;
  }
}

关于flutter - Flutter中的Singleton提供运行时错误 “Unhandled Exception: Reading static variable ' _instance @ 54532459 4' during its initialization”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60745352/

10-12 04:58