Flutter:StatefulWidget 中的范围模型访问

Flutter: scoped model access in StatefulWidget

我有范围模型 lib/scoped_models/main.dart:

import 'package:scoped_model/scoped_model.dart';

class MainModel extends Model {
  int _count = 0;

  int get count {
    return _count;
  }
  
  void incrementCount() {
    _count += 1;
    notifyListeners();
  }

  void setCount(int value) {
    _count = value;
    notifyListeners();
}

而且非常简单的应用程序 lib/main.dart:

import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:scoped_m_test/scoped_models/main.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ScopedModel<MainModel>(
        model: MainModel(),
        child: MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        )
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final MainModel _model = MainModel();

  void initState() {
    super.initState();
    // _model.incrementCount(); // <-- doesn't work !!!
  }
  
  void _incrementCounter() {
    setState(() {
      // _model.incrementCount(); // <-- doesn't work !!!
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            ScopedModelDescendant<MainModel>(
              builder: (BuildContext context, Widget child, MainModel model) {
                return Text(
                  '${model.count}',
                  style: Theme.of(context).textTheme.headline4,
                );
              }
            )
          ],
        ),
      ),
      floatingActionButton: ScopedModelDescendant<MainModel>(
        builder: (BuildContext context, Widget child, MainModel model) {
          return FloatingActionButton(
            onPressed: () {
              model.incrementCount(); // <-- only this works !!!
              // _incrementCounter(); // <-- doesn't work !!!
            },
            tooltip: 'Increment',
            child: Icon(Icons.add),
          );
        }
      )
    );
  }
}

我无法在 ScopedModelDescendant 小部件之外访问 MainModel 的问题。

如何在_MyHomePageStateclass开头调用MainModel方法?

我相信这是可能的,因为我不想将所有逻辑都保留在 MainModel class 中并调用 ScopedModelDescendant 小部件中的每个方法,因为如果有很多嵌套的小部件。

那么,如何访问 StatefulWidget 中的作用域模型?

观察我的代码一段时间后,我意识到修复它是多么愚蠢。

所以,显然项目的所有小部件和文件应该只有一个 MainModel() 实例,为了方便起见,它应该放在范围模型文件 lib/scoped_models/main.dart 中,如下所示:

import 'package:scoped_model/scoped_model.dart';

final MainModel mainModel = MainModel(); // <-- create instance once for all files which require scoped model import

class MainModel extends Model {
  int _count = 0;

  int get count {
    return _count;
  }
  
  void incrementCount() {
    _count += 1;
    notifyListeners();
  }

  void setCount(int value) {
    _count = value;
    notifyListeners();
}

然后您可以在导入模型的任何地方使用 mainModel 实例 import 'package:<app_name>/scoped_models/main.dart';

因此,此代码将有效 lib/main.dart:

import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:scoped_m_test/scoped_models/main.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ScopedModel<MainModel>(
        model: mainModel, // <-- instance of model from 'lib/<app_name>/scoped_models/main.dart'
        child: MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        )
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  void initState() {
    super.initState();
  }
  
  void _incrementCounter() {
    setState(() {
      mainModel.incrementCount(); // <-- now it works !!!
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            ScopedModelDescendant<MainModel>(
              builder: (BuildContext context, Widget child, MainModel model) {
                return Text(
                  '${model.count}',
                  style: Theme.of(context).textTheme.headline4,
                );
              }
            )
          ],
        ),
      ),
      floatingActionButton: ScopedModelDescendant<MainModel>(
        builder: (BuildContext context, Widget child, MainModel model) {
          return FloatingActionButton(
            onPressed: () {
              // model.incrementCount(); // <-- works !!!
              _incrementCounter(); // <-- now it's working too !!!
            },
            tooltip: 'Increment',
            child: Icon(Icons.add),
          );
        }
      )
    );
  }
}

尽管这似乎是合理的事实,但由于缺乏示例,这也是第一次让人不知所措。

使用作用域模型作为提供者

  • 在使用它的小部件 (MyHomePage) 之前添加 ScopedModel
  • 使用ScopedModel.of<MainModel>(context)控制模型
  • 使用ScopedModelDescendant<MainModel>听模型

使用这个的好处:

  • 您可以在后代中访问相同的模型并轻松共享数据
  • 尽可能小地重建小部件(将只重建 ScopedModelDescendant 部分)

代码:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ScopedModel<MainModel>(
        model: MainModel(),
        child: MyHomePage(title: 'Flutter Demo Home Page'),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  void initState() {
    super.initState();
  }

  void _incrementCounter() {
    ScopedModel.of<MainModel>(context).incrementCount();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('You have pushed the button this many times:'),
            ScopedModelDescendant<MainModel>(
              builder: (context,child, model){
                return Text(
                  '${model.count}',
                  style: Theme.of(context).textTheme.headline4,
                );
              },
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _incrementCounter();
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

将 MainModel 作为单例

作为您的解决方案,您创建 MainModel 一次并使其最终化。这可以像下面这样更简单:

MainModel

final MainModel mainModel = MainModel();

class MainModel{
  int _count = 0;

  int get count {
    return _count;
  }

  void incrementCount() {
    _count += 1;
  }

  void setCount(int value) {
    _count = value;
  }
}

我的主页

  • MainModel 甚至不需要扩展模型或使用 notifyListeners 因为小部件使用 setState 重建

代码:

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  void initState() {
    super.initState();
  }

  void _incrementCounter() {
    setState(() {
      mainModel.incrementCount();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '${mainModel.count}',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _incrementCounter();
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}