Flutter中的Singleton给出运行时错误“未处理的异常:在初始化期间读取静态变量'_instance @ 545324594'”

问题描述 投票:0回答:2

我试图在Flutter应用程序(Flutter版本1.12.13 + hotfix8)中实现MVP模式。我的控制器(演示者)是一个单例,看起来像这样:

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还是陌生的。也许我以错误的方式实现了单例课程?

编辑: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
    );
  }
}


flutter dart singleton mvp
2个回答
0
投票

最后,我找到了答案:我必须尽可能晚地调用小部件的构造函数。因此,我在getter函数中调用了它。工作代码如下:

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();
  Function _currentWidget;

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

  factory Controller() => _instance;

  Widget get currentWidget => this._currentWidget();

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

也许有一天它将帮助某人:)


0
投票

您具有循环依赖性。创建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; 
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.