Scoped_Model:全局State管理

Posted by アライさん on 2019年10月22日

多个model合并

1
class MainModel extends Model with AModel,BModel,CModel{}

并在flutter工程根目录下创建analysis_options.yaml

1
2
3
analyzer:
errors:
mixin_inherits_from_not_object: ignore

使用这种方法可是使Widget直接取到model

1
static CounterModel of(BuildContext context) => ScopedModel.of<CounterModel>(context);
1
CounterModel.of(context).counter

但CounterModel.of(context).counter方式获取的model,不会自动刷新。

  

  

  

异步刷新的例子

Model

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import 'package:scoped_model/scoped_model.dart';
import 'dart:async';

class CounterModel extends Model {
Timer _timer;//定时器
int timerNumber = 60;//倒计时

int _counter = 0; //计数器

int get counter => _counter;

//每秒触发一次,增加count
void increment(int count) async {
const oneSec = const Duration(seconds: 1);
_timer = new Timer.periodic(oneSec, (Timer timer) {
if (timerNumber <= 0) {
_timer.cancel();
}

_counter += count;
// 通知所有的 listener
notifyListeners();

timerNumber -= 1;
});
}
}

main.dart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import 'package:flutter/material.dart';
import 'counter_model.dart';
import 'package:scoped_model/scoped_model.dart';
import './count_page.dart';

void main() {
runApp(MyApp(
model: CounterModel(),
));
}

class MyApp extends StatelessWidget {
final CounterModel model;

const MyApp({Key key, @required this.model}) : super(key: key);

@override
Widget build(BuildContext context) {
return ScopedModel(
model: model,
child: MaterialApp(
title: 'Scoped Model Demo',
home: CountPage(),
),
);
}
}

点击发起

ScopedModelDescendant<CounterModel>(
        builder: (context, child, model) {
          return FloatingActionButton(
            onPressed: () {
               model.increment(2);
            },
            tooltip: 'add',
            child: Icon(Icons.add),
          );
        },
      ),

自动接收model变化

ScopedModelDescendant<CounterModel>(
              builder: (context, child, model) {
                return Text(
                  '${model.counter.toString()} 次了',
                  style: TextStyle(
                    color: Colors.red,
                    fontSize: 33.0,
                  ),
                );
              },
            ),