Flutter 學習筆記1【狀態共享】 mobx
阿新 • • 發佈:2020-11-28
一.引入依賴
使用mobx, flutter_mobx, mobx_codegen, build_runner
pubspec.yaml
...
dependencies
mobx
二.建立store檔案
儲存對應頁面的狀態
專案介面大致如下(按自己風格)
xxxproject/
lib/
...
store/
...
tabs.dart
三.編輯tabs.dart
tabs.dart
import 'package:mobx/mobx.dart';
/** 用於生成 tabsStore.g.dart **/
part 'tabsStore.g.dart';
class TabsStore = TabsStoreMobx with _$TabsStore;
/** 用於生成 tabsStore.g.dart **/
abstract class TabsStoreMobx with Store {
四.生成*.g.dart檔案
使用build_runner及mobx_codegen
在專案目錄下使用終端執行指令:
首次
flutter packages pub run build_runner build
每次修改到這個儲存store狀態的檔案後,都要刪除*.g.dart檔案,所以執行下面這個會方便一點
flutter packages pub run build_runner build --delete-conflicting-outputs
或者監聽store目錄的變化,自動生成
flutter packages pub run build_runner watch
此時的專案目錄如下
xxxproject/
lib/
...
store/
...
tabs.dart
tabs.g.dart
五.正式使用mobx
我想實現一個tabbar功能, 使用BottomAppBar, 每個tabs按鈕使用封裝好元件作為子元件
父元件 Tabs.dart
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_salted_fish/components/BottomAppBarItem.dart';
import 'package:flutter_salted_fish/pages/tabs/AddAction.dart';
import 'package:flutter_salted_fish/pages/tabs/Home.dart';
import 'package:flutter_salted_fish/pages/tabs/Mine.dart';
import 'package:flutter_salted_fish/pages/tabs/Msg.dart';
import 'package:flutter_salted_fish/pages/tabs/PlayGood.dart';
import 'package:flutter_salted_fish/store/tabsStore.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
class Tabs extends StatefulWidget {
Tabs({Key key}) : super(key: key);