为了弄懂Flutter的状态管理, 我用10种方法改造了counter app

Flutter快学快用24讲--08 状态管理:Flutter 状态管理及对比选型 以上就是本课时的所有内容,学完本课时你需要掌握使用状态管理的场景,常见的状态管理有哪些。本课时的核心是需要你掌握 Provider 的状态管理技术方案。至此,我已经将组件的设计基本介绍完毕,接下来我将介绍组件的单元测试,以及完善组件功能。如果你有疑问,可以在下方留言。点击此链接查看本课时源码。 阅读详情

本文通过改造flutter的counter app, 展示不同的状态管理方法的用法.

可以直接去demo地址看代码:
https://github.com/mengdd/counter_state_management
切换分支对应不同的实现方式.

Contents

  • Flutter中的状态管理
    • 状态分类
    • 状态管理方法概述
  • Counter sample默认实现: StatefulWidget
  • InheritedWidget
  • Scoped Model
  • Provider
  • BLoC
    • BLoC手动实现
    • BLoC + InheritedWidget做传递
    • BLoC rxdart实现
    • BLoC用库实现
  • rxdart
  • Redux
  • MobX
  • Flutter Hooks
  • Demo说明及感想

Flutter State Management

Flutter是描述性的(declarative), UI反映状态.

UI = f(state)

其中f代表了build方法.

状态的改变会直接触发UI的重新绘制.

UI reacts to the changes.

相对的, Android, iOS等都是命令式的(imperative), 会有setText()之类的方法来改变UI.

状态分类

状态分两种:

  • Ephemeral state: 有时也叫UI state或local state. 这种可以包含在单个widget里.
    比如: PageView的当前页, 动画的当前进度, BottomNavigationBar的当前选中tab.
    这种状态不需要使用复杂的状态管理手段, 只要用一个StatefulWidget就可以了.
  • App state: 需要在很多地方共享的状态, 也叫shared state或global state.
    比如: 用户设置, 登录信息, 通知, 购物车, 新闻app中的已读/未读状态等.

这种状态分类其实没有一个清晰的界限.
在简单的app里, 可以用setState()来管理所有的状态; 在app需要的时候, tab的index也可能被抽取到外部作为一个需要保存和管理的app state.

状态管理方法

官方提供了一些options: Flutter官方文档 options
目前官方比较推荐的是provider.

各种状态管理方法要解决的几个问题:

  • 状态保存哪里?
  • 状态如何获取?
  • UI如何更新?
  • 如何改变状态?

Counter Sample默认实现: StatefulWidget

新建Flutter app, 是一个counter app, 自动使用了StatefulWidget来管理状态.
对这个简单的app来说, 这是很合理的.

我们对这个app进行一个简单的改造, 再增加一个button用来减数字.
同样的方式, 只需要添加一个方法来做减法就可以了.

这种方法的一个变体是, 用StatefulBuilder, 主要好处是少写一些代码.

StatefulWidget对简单的Widget内部状态来说是合理的.

对于复杂的状态, 这种方式的缺点:

  • 状态属性多了以后, 可能有很多地方都在调用setState().
  • 不能把状态和UI分开管理.
  • 不利于跨组件/跨页面的状态共享. (如何调用另一个Widget的setState()? 把方法通过构造传递过来? No, don't do this!)

千万不要用全局变量法来解决问题.

如果企图用这种方式来管理跨组件的状态, 就难免会用这些Anti patterns:

  • 紧耦合. Strongly coupling widgets.
  • 全局保存的state. Globally tracking state.
  • 从外部调用setState方法. Calling setState from outside.

所以这种方法只适用于local state的管理.

InheritedWidget

InheritedWidget的主要作用是在Widget树中有效地传递信息.

如果没有InheritedWidget, 我们想把一个数据从widget树的上层传到某一个child widget, 要利用途中的每一个构造函数, 一路传递下来.

Flutter中常用的Theme, Style, MediaQuery等就是inherited widget, 所以在程序里的各种地方都可以访问到它们.

InheritedWidget也会用在其他状态管理模式中, 作为传递数据的方法.

InheritedWidget状态管理实现

当用InheritedWidget做状态管理时, 基本思想就是把状态提上去.
当子widgets之间需要共享状态, 那么就把状态保存在它们共有的parent中.

首先定义一个InheritedWidget的子类, 包含状态数据.
覆写两个方法:

  • 提供一个静态方法给child用于获取自己. (命名惯例of(BuildContext)).
  • 判断是否发生了数据更新.
class CounterStateContainer extends InheritedWidget {
  final CounterModel data;

  CounterStateContainer({
    Key key,
    @required Widget child,
    @required this.data,
  }) : super(key: key, child: child);

  @override
  bool updateShouldNotify(CounterStateContainer oldWidget) {
    return data.counter.value != oldWidget.data.counter.value;
  }

  static CounterModel of(BuildContext context) {
    return context
        .dependOnInheritedWidgetOfExactType<CounterStateContainer>()
        .data;
  }
}

之后用这个CounterStateContainer放在上层, 包含了数据和所有状态相关的widgets.
child widget不论在哪一层都可以方便地获取到状态数据.

  Text(
    '${CounterStateContainer.of(context).counter.value}',
  ),

代码分支: inherited-widget.

InheritedWidget缺点

InheritedWidget解决了访问状态和根据状态更新的问题, 但是改变state却不太行.

  • accessing state
  • updating on change
  • mutating state -> X

首先, 不支持跨页面(route)的状态, 因为widget树变了, 所以需要进行跨页面的数据传递.

其次, InheritedWidget它包含的数据是不可变的, 如果想让它跟踪变化的数据:

  • 把它包在一个StatefulWidget里.
  • 在InheritedWidget中使用ValueNotifier, ChangeNotifier或steams.

这个方案也是了解一下, 实际的全局状态管理还是用更成熟的方案.
但是它的原理会被用到其他方案中作为对象传递的方式.

Scoped Model

scoped model是一个外部package: https://pub.dev/packages/scoped_model
Scoped Model是基于InheritedWidget的. 思想仍然是把状态提到上层去, 并且封装了状态改变的通知部分.

Scoped Model实现

它官方提供例子就是改造counter: https://pub.dev/packages/scoped_model#-example-tab-

  • 添加scoped_model依赖.
  • 创建数据类, 继承Model.
import 'package:scoped_model/scoped_model.dart';

class CounterModel extends Model {
  int _counter = 0;

  int get counter => _counter;

  void increment() {
    _counter++;
    notifyListeners();
  }

  void decrement() {
    _counter--;
    notifyListeners();
  }
}

其中数据变化的部分会通知listeners, 它们收到通知后会rebuild.

在上层初始化并提供数据类, 用ScopeModel.

访问数据有两种方法:

  • 用ScopedModelDescendant包裹widget.
  • 用ScopedModel.of静态方法.

使用的时候注意要提供泛型类型, 会帮助我们找到离得最近的上层ScopedModel.

  ScopedModelDescendant<CounterModel>(
      builder: (context, child, model) {
    return Text(
      model.counter.toString(),
    );
  }),

数据改变后, 只有ScopedModelDescendant会收到通知, 从而rebuild.

ScopedModelDescendant有一个rebuildOnChange属性, 这个值默认是true.
对于button来说, 它只是控制改变, 自身并不需要重绘, 可以把这个属性置为false.

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

scoped model这个库帮我们解决了数据访问和通知的问题, 但是rebuild范围需要自己控制.

  • access state
  • notify other widgets
  • minimal rebuild -> X -> 因为需要开发者自己来决定哪一部分是否需要被重建, 容易被忘记.

代码分支: scoped-model

Provider

Provider是官方文档的例子用的方法.
去年的Google I/O 2019也推荐了这个方法.
和BLoC的流式思想相比, Provider是一个观察者模式, 状态改变时要notifyListeners().

有一个counter版本的sample: https://github.com/flutter/samples/tree/master/provider_counter

Provider的实现在内部还是利用了InheritedWidget.
Provider的好处: dispose指定后会自动被调用, 支持MultiProvider.

Provider实现

  • model类继承ChangeNotifer, 也可以用with.
class CounterModel extends ChangeNotifier {
  int value = 0;

  void increment() {
    value++;
    notifyListeners();
  }

  void decrement() {
    value--;
    notifyListeners();
  }
}
  • 数据提供者: ChangeNotifierProvider.
void main() => runApp(ChangeNotifierProvider(
      create: (context) => CounterModel(),
      child: MyApp(),
    ));
  • 数据消费者/操纵者, 有两种方式: Consumer包裹, 用Provider.of.
  Consumer<CounterModel>(
    builder: (context, counter, child) => Text(
      '${counter.value}',
    ),
  ),

FAB:

  FloatingActionButton(
    onPressed: () =>
        Provider.of<CounterModel>(context, listen: false).increment(),
  ),

这里listen置为false表明状态变化时并不需要rebuild FAB widget.

Provider性能相关的实现细节

  • Consumer包裹的范围要尽量小.
  • listen变量.
  • child的处理. Consumer中builder方法的第三个参数.

可以用于缓存一些并不需要重建的widget:

return Consumer<CartModel>(
  builder: (context, cart, child) => Stack(
        children: [
          // Use SomeExpensiveWidget here, without rebuilding every time.
          child,
          Text("Total price: ${cart.totalPrice}"),
        ],
      ),
  // Build the expensive widget here.
  child: SomeExpensiveWidget(),
);

代码分支: provider.

BLoC

BLoC模式的全称是: business logic component.

所有的交互都是a stream of asynchronous events.
Widgets + Streams = Reactive.

BLoC的实现的主要思路: Events in -> BloC -> State out.

Google I/O 2018上推荐的还是这个, 2019就推荐Provider了.
当然也不是说这个模式不好, 架构模式本来也没有对错之分, 只是技术选型不同.

BLoC手动实现

不添加任何依赖可以手动实现BLoC, 利用:

  • Dart SDK > dart:async > Stream.
  • Flutter的StreamBuilder: 输入是一个stream, 有一个builder方法, 每次stream中有新值, 就会rebuild.

可以有多个stream, UI只在自己感兴趣的信息发生变化的时候重建.

BLoC中:

  • 输入事件: Sink<Event> input.
  • 输出数据: Stream<Data> output.

CounterBloc类:

class CounterBloc {
  int _counter = 0;

  final _counterStateController = StreamController<int>();

  StreamSink<int> get _inCounter => _counterStateController.sink;

  Stream<int> get counter => _counterStateController.stream;

  final _counterEventController = StreamController<CounterEvent>();

  Sink<CounterEvent> get counterEventSink => _counterEventController.sink;

  CounterBloc() {
    _counterEventController.stream.listen(_mapEventToState);
  }

  void _mapEventToState(CounterEvent event) {
    if (event is IncrementEvent) {
      _counter++;
    } else if (event is DecrementEvent) {
      _counter--;
    }
    _inCounter.add(_counter);
  }

  void dispose() {
    _counterStateController.close();
    _counterEventController.close();
  }
}

有两个StreamController, 一个控制state, 一个控制event.

读取状态值要用StreamBuilder:

  StreamBuilder(
    stream: _bloc.counter,
    initialData: 0,
    builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
      return Text(
        '${snapshot.data}',
      );
    },
  )

而改变状态是发送事件:

  FloatingActionButton(
    onPressed: () => _bloc.counterEventSink.add(IncrementEvent()),
  ),

实现细节:

  • 每个屏幕有自己的BLoC.
  • 每个BLoC必须有自己的dispose()方法. -> BLoC必须和StatefulWidget一起使用, 利用其生命周期释放.

代码分支: bloc

BLoC传递: 用InheritedWidget

手动实现的BLoC模式, 可以结合InheritedWidget, 写一个Provider, 用来做BLoC的传递.

代码分支: bloc-with-provider

BLoC rxdart实现

用了rxdart package之后, bloc模块的实现可以这样写:

class CounterBloc {
  int _counter = 0;

  final _counterSubject = BehaviorSubject<int>();

  Stream<int> get counter => _counterSubject.stream;

  final _counterEventController = StreamController<CounterEvent>();

  Sink<CounterEvent> get counterEventSink => _counterEventController.sink;

  CounterBloc() {
    _counterEventController.stream.listen(_mapEventToState);
  }

  void _mapEventToState(CounterEvent event) {
    if (event is IncrementEvent) {
      _counter++;
    } else if (event is DecrementEvent) {
      _counter--;
    }
    _counterSubject.add(_counter);
  }

  void dispose() {
    _counterSubject.close();
    _counterEventController.close();
  }
}

BehaviorSubject也是一种StreamController, 它会记住自己最新的值, 每次注册监听, 会立即给你最新的值.

代码分支: bloc-rxdart.

BLoC Library

可以用这个package来帮我们简化代码: https://pub.dev/packages/flutter_bloc

自己只需要定义Event和State的类型并传入, 再写一个逻辑转化的方法:

class CounterBloc extends Bloc<CounterEvent, CounterState> {
  @override
  CounterState get initialState => CounterState.initial();

  @override
  Stream<CounterState> mapEventToState(CounterEvent event) async* {
    if (event is IncrementEvent) {
      yield CounterState(counter: state.counter + 1);
    } else if (event is DecrementEvent) {
      yield CounterState(counter: state.counter - 1);
    }
  }
}

用BlocProvider来做bloc的传递, 从而不用在构造函数中一传到底.

访问的时候用BlocBuilder或BlocProvider.of<CounterBloc>(context).

  BlocBuilder(
    bloc: BlocProvider.of<CounterBloc>(context),
    builder: (BuildContext context, CounterState state) {
      return Text(
        '${state.counter}',
      );
    },
  ),

这里bloc参数如果没有指定, 会自动向上寻找.

BlocBuilder有一个参数condition, 是一个返回bool的函数, 用来精细控制是否需要rebuild.

  FloatingActionButton(
    onPressed: () =>
        BlocProvider.of<CounterBloc>(context).add(IncrementEvent()),
  ),

代码分支: bloc-library.

rxdart

这是个原始版本的流式处理.

和BLoC相比, 没有专门的逻辑模块, 只是改变了数据的形式.

利用rxdart, 把数据做成流:

class CounterModel {
  BehaviorSubject _counter = BehaviorSubject.seeded(0);

  get stream$ => _counter.stream;

  int get current => _counter.value;

  increment() {
    _counter.add(current + 1);
  }

  decrement() {
    _counter.add(current - 1);
  }
}

获取数据用StreamBuilder, 包围的范围尽量小.

    StreamBuilder(
      stream: counterModel.stream$,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        return Text(
          '${snapshot.data}',
        );
      },
    ),

Widget dispose的时候会自动解绑.

数据传递的部分还需要进一步处理.

代码分支: rxdart.

Redux

Redux是前端流行的, 一种单向数据流架构.

概念:

  • Store: 用于存储State对象, 代表整个应用的状态.
  • Action: 事件操作.
  • Reducer: 用于处理和分发事件的方法, 根据收到的Action, 用一个新的State来更新Store.
  • View: 每次Store接到新的State, View就会重建.

Reducer是唯一的逻辑处理部分, 它的输入是当前State和Action, 输出是一个新的State.

Flutter Redux状态管理实现

首先定义好action, state:

enum Actions {
  Increment,
  Decrement,
}

class CounterState {
  int _counter;

  int get counter => _counter;

  CounterState(this._counter);
}

reducer方法根据action和当前state产生新的state:

CounterState reducer(CounterState prev, dynamic action) {
  if (action == Actions.Increment) {
    return new CounterState(prev.counter + 1);
  } else if (action == Actions.Decrement) {
    return new CounterState(prev.counter - 1);
  } else {
    return prev;
  }
}

  • 数据提供者: StoreProvider.
    放在上层:
   StoreProvider(
    store: store,
    child: MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    ),
  );
  • 数据消费者: StoreConnector, 可读可写.

读状态:

    StoreConnector<CounterState, String>(
      converter: (store) => store.state.counter.toString(),
      builder: (context, count) {
        return Text(
          '$count',
        );
      },
    )

改变状态: 发送action:

    StoreConnector<CounterState, VoidCallback>(
      converter: (store) {
        return () => store.dispatch(action.Actions.Increment);
      },
      builder: (context, callback) {
        return FloatingActionButton(
          onPressed: callback,
        );
      },
    ),

代码分支: redux.

MobX

MobX本来是一个JavaScript的状态管理库, 它迁移到dart的版本: mobxjs/mobx.dart.

核心概念:

  • Observables
  • Actions
  • Reactions

MobX状态管理实现

官网提供了一个counter的指导: https://mobx.netlify.com/getting-started

这个库的实现需要先生成一些代码.
先写类:

import 'package:mobx/mobx.dart';

part 'counter.g.dart';

class Counter = _Counter with _$Counter;

abstract class _Counter with Store {
  @observable
  int value = 0;

  @action
  void increment() {
    value++;
  }

  @action
  void decrement() {
    value--;
  }
}

运行命令flutter packages pub run build_runner build, 生成counter.g.dart.

改完之后就不需要再使用StatefulWidget了.

找一个合适的地方初始化数据对象并保存:

final counter = Counter();

读取值的地方用Observer包裹:

Observer(
  builder: (_) => Text(
    '${counter.value}',
    style: Theme.of(context).textTheme.display1,
  ),
),

改变值的地方:

  FloatingActionButton(
    onPressed: counter.increment,
    tooltip: 'Increment',
    child: Icon(Icons.add),
  ),

代码分支: mobx.

Flutter hooks

React hooks的Flutter实现.
package: https://pub.dev/packages/flutter_hooks

Hooks存在的目的是为了增加widgets之间的代码共享, 取代StatefulWidget.

首页的例子是: 对一个使用了AnimationController的StatefulWidget的简化.

flutter_hooks包中已经内置了一些已经写好的hooks.

Flutter hooks useState

counter demo一个最简单的改法, 就是将StatefulWidget改为HookWidget.

在build方法里:

final counter = useState(0);

调用useState方法设定一个变量, 并设定初始值, 每次值改变的时候widget会被rebuild.

使用值:

  Text(
    '${counter.value}',
  ),

改变值:

  FloatingActionButton(
    onPressed: () => counter.value++,
  ),

实际上是把StatefulWidget包装了一下, 在初始化Hook的时候注册了listener, 数据改变的时候调用setState()方法.
只是把这些操作藏在hook里, 不需要开发者手动调用而已.

所以本质上还是StatefulWidget, 之前解决不了的问题它依然解决不了.

代码分支: flutter-hooks.

Demo

本文demo地址: https://github.com/mengdd/counter_state_management
每个分支对应一种实现. 切换不同分支查看不同的状态管理方法.

对于代码的说明:
这是counter app用不同的状态管理模式进行的改造.
因为这个demo的逻辑和UI都比较简单, 可能实际上并不需要用上一些复杂的状态管理方法, 有种杀鸡用牛刀的感觉.
只是为了保持简单来突出状态管理的实现, 说明用法.

一些自己的感想

老实说, 做了这么多年Android, 各种构架MVP, MVVM, MVI, 目的就是数据和逻辑分离, 逻辑和UI分离,
所以初识Flutter的时候对这种万物皆widget, 一个树里面包含一切的方式有点怀疑, UI逻辑数据写成一堆, 程序功能复杂后, 肯定会越写越乱.

但是了解了它的状态管理之后, 发现Flutter的状态管理就是它的程序构架, 并且也是百家争鸣各取所需.
只是Flutter的构架是服务于Flutter framework的设计思想的, 要遵从利用它, 而不是与之反抗.
爱它如是, 而不是如我所愿.

印证了一些道理:

  • 不要只喜欢自己熟悉的东西.
  • 了解之后才有发言权.

参考

Google I/O

InheritedWidget

Scoped Model

provider

Bloc

Redux

MobX

推荐阅读:腾讯技术团队整理,万字长文轻松彻底入门 Flutter,秒变大前端
原文作者:圣骑士wind
原文链接:https://www.cnblogs.com/mengdd/p/flutter-state-management.html

MATLAB MinGW-w64 C/C++ 编译器 手动安装配置 根据Matlab版本与MinGW版本对应关系,手动安装、配置并测试MinGW 阅读详情

相关推荐

librealsense2 camera.so: undefined symbol:ZN2cV3MatC1EV解决笔记记录

先参考的这个兄弟的办法虽然没解决但是提供了大方向感谢; realsenseD400系列相机报错:undefined symbol: _ZN2cv3MatC1EiiiRKNS_7Scalar_IdEE解决方案 后解决办法参考 No GPU usage on jetson xavier NX · Issue #2326 · IntelRealSense/realsense-ros · GitHubOpenCV_DIR" to a directory containing one of the above f

梁俊星的博客 3522

Flutter中的异步方式

前言 最近用 Flutter 写了一段时间的业务代码,遇到了很多之前写简单代码没遇到的问题,比如说: 如何使用 Flutter 调原生 如何选择状态管理和事件管理 如何画出自己想要的View ... 上面中的很多场景,都会涉及到异步知识。 我们在写 Flutter 的时候,也会需要异步处理问题,比如说文件处理、网络请求、加载图片等。 一、Flutter中的异步机制 isolate 这个词对于 Flutter 新手来说可能有些陌生,它其实是 Dart 中的线程机制。 1. 单线程模型 Dart 是一种基

qq_35063091的博客 3470

Unity六边形网格A*寻路实战:从坐标转换到算法优化

寻路算法是游戏开发与AI领域的核心技术,它决定了智能体在虚拟空间中的移动决策能力。A*算法作为启发式搜索的经典实现,通过结合实际代价与预估代价,能在复杂环境中高效找到最优路径。其技术价值在于平衡了搜索效率与结果最优性,广泛应用于策略游戏、机器人导航和自动化规划等场景。在游戏开发中,六边形网格因其移动自然、邻接均衡的特性,常被用于《文明》等经典策略游戏的地图设计。本文聚焦于Unity环境下,针对尖头朝上六边形网格的A*寻路实现,深入解析了轴向坐标系的选型、邻居计算的优化策略以及地形代价的融合方法,为战棋类或策

weixin_29017445的博客 299

【-Flutter/Dart 语法补遗-】 sync* 和 async* 、yield 和yield* 、async 和 await

前言 类别 关键字 返回类型 搭档 多元素同步 sync* Iterable<T> yield、yield* 单元素异步 async Future<T> await 多元素异步 async* Stream<T> yield、yield* 、await 下面就用几个emoji,认识一下这几个关键字吧 一、多元素同步函数生成器 1...

张风捷特烈的博客 4119

手把手教你用Verilog实现AT24C64的I2C读写(附完整仿真流程)

本文详细介绍了如何使用Verilog HDL设计AT24C64 EEPROM的I2C控制器,并配合ModelSim完成完整的仿真验证流程。内容涵盖I2C协议解析、Verilog状态机设计、AT24C64读写操作实现,以及仿真波形分析和调试技巧,为FPGA开发者提供了一套完整的EEPROM控制解决方案。

3c4x5z6v7b的博客 853

3分钟搞懂欧式距离变换(EDT):从暴力算法到Felzenszwalb的演进史

本文系统梳理了欧式距离变换(EDT)从暴力算法到高效线性算法的演进历程。重点解析了光栅扫描算法和Felzenszwalb算法的核心思想与实现,并探讨了其在机器人路径规划中生成欧几里得符号距离场(ESDF)的关键应用,为开发者提供了清晰的算法选型与实战指南。

fern8的博客 985

Flutter中多种状态管理方案

Flutter中有多种状态管理方案,用于管理应用程序中的状态和数据,以确保应用的可维护性和可扩展性。以下是一些常见的Flutter状态管理方法:

m0_59162559的博客 1582

ModuleNotFoundError: No module named‘langchain.schema.output parserlangchain.schema is not a package

电脑里现有的langchain库版本与import所需的不同,卸载原有langchain,重新下载最新的langchain。在步骤1后,若仍不可运行。在确保已重新下载新langchain后,重启python后,可正常运行。在版本号中填入所需的langchain版本号,可在requirements.txt查看。运行如下代码时,出现error。

weixin_45751925的博客 1717

Flutter中状态管理选项的比较:利弊探索

Flutter 应用程序开发的一个关键方面是管理状态,这确保了整个应用程序的数据一致性和更新。然而,Flutter 提供了多种状态管理解决方案,每种解决方案都有自己的优缺点。在这篇博客中,我们将探讨 Flutter 中一些流行的状态管理选项,并讨论它们的优缺点。

前端全栈开发者 1740

全新YOLOv11一文弄懂 | YOLOv11网络结构解读 、yolov11.yaml配置文件详细解读与说明、模型训练参数详细解析 | 通俗易懂!入门必看系列!

本文全面介绍了YOLOv11目标检测算法,包含网络结构解析、yaml配置文件详解及训练教程。YOLOv11通过改进的C3k2f模块、SPPF和C2PSA注意力机制等创新设计,在COCO数据集上实现了比YOLOv8更优的性能。文章详细解读了yolov11.yaml配置文件的参数设置、主干网络(backbone)和头部网络(head)结构,并提供了完整的训练代码示例和参数说明。训练部分涵盖了模型选择、参数设置及优化技巧,包括epochs、batch size、学习率等关键参数的调整建议。最后总结了YOLOv11

Ai缝合怪、助力小伙伴高效发论文 3万+

Arduino、ESP32驱动AS3935数字闪电传感器(闪电传感器)

闪电传感器采用AMS独具创新的AS3935数字闪电传感芯片与Coilcraft的MA5532-AE专用天线,可在室内或室外,安全地检测方圆40km范围内发生闪电的距离,闪电相对强度与统计闪电发生次数。

不脱发的程序猿 2021

为了弄懂Flutter的状态管理,-我用10种方法改造了counter-app

所以这种方法只适用于local state的管理.InheritedWidget的主要作用是在Widget树中有效地传递信息.如果没有, 我们想把一个数据从widget树的上层传到某一个child widget, 要利用途中的每一个构造函数, 一路传递下来.Flutter中常用的, , 等就是inherited widget, 所以在程序里的各种地方都可以访问到它们.也会用在其他状态管理模式中, 作为传递数据的方法.当用做状态管理时, 基本思想就是把状态提上去. 当子widgets之间需要共享状态, 那么就

2401_84003941的博客 640

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

为了弄懂Flutter的状态管理, 我用10种方法改造了counter app(1)

我见过很多技术leader在面试的时候,遇到处于迷茫期的大龄程序员,比面试官年龄都大。这些人有一些共同特征:可能工作了7、8年,还是每天重复给业务部门写代码,工作内容的重复性比较高,没有什么技术含量的工作。问到这些人的职业规划时,他们也没有太多想法。其实30岁到40岁是一个人职业发展的黄金阶段,一定要在业务范围内的扩张,技术广度和深度提升上有自己的计划,才有助于在职业发展上有持续的发展路径,而不至于停滞不前。不断奔跑,你就知道学习的意义所在!

2401_84123077的博客 891

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

为了弄懂Flutter的状态管理, 我用10种方法改造了counter app(2)

总而言之,成功是留给准备好的人的。无论是参加什么面试,都要做好充足的准备,注意好面试的礼仪和穿着,向面试官表现出自己的热忱与真诚就好。即使最后没有过关,也要做好经验的总结,为下一次面试做好充足准备。这里我为大家准备了一些我在面试后整理的面试专题资料,除了面试题,还总结出了互联网公司Android程序员面试涉及到的绝大部分面试题及答案,并整理做成了文档,以及系统的进阶学习视频资料分享给大家,希望能帮助到你面试前的复习,且找到一个好的工作,也节省大家在网上搜索资料的时间来学习。

2401_84123094的博客 760

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

为了弄懂Flutter的状态管理,-我用10种方法改造了counter-app(2)

感觉现在好多人都在说什么安卓快凉了,工作越来越难找了。又是说什么程序员中年危机啥的,为啥我这年近30的老农根本没有这种感觉,反倒觉得那些贩卖焦虑的都是瞎j8扯谈。当然,职业危机意识确实是要有的,但根本没到那种草木皆兵的地步好吗?Android凉了都是弱者的借口和说辞。虽然 Android 没有前几年火热了,已经过去了会四大组件就能找到高薪职位的时代了。

2301_79055239的博客 1122
上一篇: 简历投递审核都不通过,千万别让简历埋没了你的才能!
下一篇: 2020最新BAT Android高端技术面试145题详解
Python_林一
博客等级 码龄7年 904粉丝 510原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址