flutter基礎(chǔ)集錦

View篇

有幾種視圖框架

總體來(lái)說(shuō)有兩種,Column和Row,前者表示豎直方向,后者表示水平方向。

怎么實(shí)現(xiàn)類(lèi)似wrap_content和match_parent的效果

Widget parent = Container(
  width: 360,
  height: 360,
  color: Colors.lightGreen,
  child: Column(
    mainAxisSize: MainAxisSize.max,
    children: <Widget>[
      Container(
        width: 120,
        height: 86,
        color: Colors.brown,
      ),
      Container(
        width: 120,
        height: 86,
        color: Colors.red,
      ),
      Container(
        width: 120,
        height: 86,
        color: Colors.cyan,
      ),
    ],
  ),
);

可以看到Container里面包含的Column面積設(shè)置的多大就展示多大的區(qū)域,主要起作用的是mainAxisSize和mainAxisAlignment參數(shù)。

image

mainAxisSize

表示剩余空間的占用情況,是最大限度(max)還是最小限度(min)的占用剩余空間

mainAxisAlignment

表示Column或Row里面子布局相互之間的空間應(yīng)該怎么分布。

  • MainAxisAlignment.start 表示所有子控件往首部的區(qū)域集中,剩余空間集中在尾部
  • MainAxisAlignment.spaceBetween 表示所有子控件之間平分剩余的空間,不包含首尾
  • MainAxisAlignment.center 表示剩余的空間平均分配到子控件的首胃,而子控件之間沒(méi)有空間
  • MainAxisAlignment.spaceEvenly 表示子控件之間,包含首尾都要均分剩余空間
  • MainAxisAlignment.end 表示所有子控件往尾部的區(qū)域集中,剩余空間集中在首部
  • MainAxisAlignment.spaceAround 剩余空間除以子控件數(shù)量 + 1,子控件之間的間距是等分的,多出來(lái)的空間除以2,分布于子控件的首尾。比如剩余空間是42,有2個(gè)子控件,控件之間的間隔是42 / (2 + 1) = 14,控件之間的間距是14,而兩個(gè)控件前后的間隔是14 / 2 = 7.

crossAxisAlignment

這個(gè)參數(shù)決定了與排布方向垂直方向子控件的位置。與mainAxisAlignment是相對(duì)的。

image

還是利用上面的代碼做例子說(shuō)明:

Widget parent = Container(
  width: 360,
  height: 360,
  color: Colors.lightGreen,
  child: Column(
    mainAxisSize: MainAxisSize.max,
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    crossAxisAlignment: CrossAxisAlignment.end,
    children: <Widget>[
      Container(
        width: 120,
        height: 86,
        color: Colors.brown,
      ),
      Container(
        width: 120,
        height: 86,
        color: Colors.red,
      ),
      Container(
        width: 120,
        height: 86,
        color: Colors.cyan,
      ),
    ],
  ),
);

子控件之間和首尾都有了空間,另外子控件對(duì)齊最右邊。如下:


image

到這里,我們就知道,Column的Main方向是豎直的,Cross方向是水平的,而Row正好相反,Main方向是水平的,Cross方向是豎直的。

綜述一下,要實(shí)現(xiàn)wrap_content效果就設(shè)置mainAxisSize為min,并且mainAxisAlignment設(shè)置為start;要實(shí)現(xiàn)match_parent就設(shè)置mainAxisSize為max,并且mainAxisAlignment不要設(shè)置為start或end或center。

怎么設(shè)置視圖的寬高

一般情況下使用Container里面的width和height設(shè)置寬高。

當(dāng)然了,如果不想設(shè)置具體的寬高,只想設(shè)置一個(gè)大體的約束,可以設(shè)置Container里面的constraints屬性,這個(gè)屬性對(duì)應(yīng)的類(lèi)是BoxConstraints類(lèi),這個(gè)類(lèi)有四個(gè)參數(shù)可以設(shè)置,如下:

BoxConstraints(
    minHeight: 360, 
    minWidth: 360, 
    maxWidth: 360, 
    maxHeight: 360);

怎么設(shè)置控件的背景顏色

Container里面有color參數(shù)可以設(shè)置背景顏色,前提是Container沒(méi)有顯式的設(shè)置decoration屬性。

decoration屬性用于為Container設(shè)置裝飾,這個(gè)裝飾屬性對(duì)應(yīng)的是BoxDecoration類(lèi),如果設(shè)置了這個(gè)屬性就不能在Container中設(shè)置color的值了,只能通過(guò)decoration設(shè)置。

怎么設(shè)置點(diǎn)擊之后的波紋效果

InkWell可以滿(mǎn)足需求,父Widget用InkWell,然后child參數(shù)設(shè)置為要點(diǎn)擊的子Widget。

怎么設(shè)置字體以及富文本

  • 普通文本
Text(
    "flutter教程",
    textAlign: TextAlign.center,
    style: TextStyle(
      fontSize: 12,
      color: Colors.lightGreenAccent,
      fontWeight: FontWeight.bold,
      decoration: TextDecoration.lineThrough,
    ),
)
  • 富文本
RichText(
    text: TextSpan(
        text: "first text",
        style: TextStyle(color: Colors.white, fontSize: 18),
        children: <TextSpan>[
          TextSpan(
            text: "second text",
            style: TextStyle(color: Colors.red, fontSize: 12),
          ),
        ],
    ),
);

怎么設(shè)置控件圓角

Container(
    decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(12)))
);

怎么將控件背景設(shè)置為我想要的icon

Container(
  decoration: BoxDecoration(
    image: DecorationImage(
      image: AssetImage("images/your image source.png"),
      fit: BoxFit.cover,
    ),
  ),
);

怎么設(shè)置控件背景漸變

Container(
  decoration: BoxDecoration(
    gradient: LinearGradient(
        begin: Alignment.centerLeft,//起始方向
        end: Alignment.centerRight,//終止方向
        colors: [
          ColorUtil.hexToColor("#FF8602"),
          ColorUtil.hexToColor("#FE3F01")
    ]),
  ),
);

怎么為控件設(shè)置點(diǎn)擊事件

Widget backWidget = GestureDetector(
  child: Image.asset(
    "images/your image source",
    width: 24,
    height: 24,
  ),
  onTap: () => Navigator.of(context).pop(),//your own action
);

控件怎么居中

  • 第一種方法
Align(
    alignment: Alignment.center,
    child: Text(
      "flutter教程",
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: 12,
        color: Colors.lightGreenAccent,
        fontWeight: FontWeight.bold,
        decoration: TextDecoration.lineThrough,
      ),
    ),
);
  • 第二種方法
Center(
    child: Text(
      "flutter教程",
      textAlign: TextAlign.center,
      style: TextStyle(
        fontSize: 12,
        color: Colors.lightGreenAccent,
        fontWeight: FontWeight.bold,
        decoration: TextDecoration.lineThrough,
      ),
    ),
)

控件怎么設(shè)置上下左右的margin

Widget parent = Container(
  margin: EdgeInsets.only(top: 40, bottom:40, left:40, right:40),
  child: childWidget,
);

控件怎么設(shè)置padding

Padding(
    child: Text("your own widget")
    padding: EdgeInsets.only(top: 40, bottom:40, left:40, right:40),
),

圖片怎么設(shè)置圓角

ClipRRect(
  borderRadius: new BorderRadius.circular(8.0),
  child: Image.network(
    goodsImage,
    width: 80,
    height: 80,
   ),
),

列表怎么用

  • ListView.builder
ListView.builder(
    itemBuilder: (context, index) {
      return Text("your child list item widget");
    },
    itemCount: dataSet.length,
),
  • ListView.separated可以設(shè)置子item之間的分割,separatorBuilder屬性返回間隔widget
Widget parent = ListView.separated(
    itemBuilder: (BuildContext context, int index) {
      return Text("this is index $index");
    },
    separatorBuilder: (BuildContext context, int index) {
      return Container(
        width: 360,
        height: 8,
        color: Colors.green,
      );
    },
    itemCount: 20);
  • ListView.custom可以自定義子item的展現(xiàn)模式
Widget parent = ListView.custom(
  childrenDelegate: SliverChildBuilderDelegate(
    (BuildContext context, int index) {
      return Text("this is index $index");
    },
    childCount: 20,
  ),
);

滾動(dòng)視圖怎么用

  • SingleChildScrollView 只能包含有一個(gè)child
Widget parent = SingleChildScrollView(
  child: Column(
    children: <Widget>[
      Container(
        color: Colors.blue,
        child: Text("this is 1"),
        width: 360,
        height: 240,
      ),
      Container(
        color: Colors.red,
        child: Text("this is 2"),
        width: 360,
        height: 240,
      ),
      Container(
        color: Colors.green,
        child: Text("this is 3"),
        width: 360,
        height: 240,
      ),
      Container(
        color: Colors.cyan,
        child: Text("this is 4"),
        width: 360,
        height: 240,
      ),
      Container(
        color: Colors.yellow,
        child: Text("this is 5"),
        width: 360,
        height: 240,
      ),
    ],
  ),
);
  • CustomScrollView 這個(gè)控件比較強(qiáng)大,里面可以有多個(gè)child widget,并且必須是sliver屬性的控件。

不包含appBar

CustomScrollView(
    controller: _scrollController,
    slivers: <Widget>[
      SliverList(
          delegate: SliverChildBuilderDelegate(
        (context, index) {
          return Text("child item");
        },
        childCount: dataSet.length,
      )),
      SliverToBoxAdapter(child: footerView),
    ],
);

其實(shí)有sliver屬性的控件還有SliverGrid,SliverAppBar等。

  • NestedScrollView 有收縮伸展appBar能力的滾動(dòng)控件
Widget childContent = NestedScrollView(
    headerSliverBuilder: (context, innerBoxIsScrolled) => [
          SliverOverlapAbsorber(
            child: SliverSafeArea(
              top: false,
              sliver: SliverAppBar(
                backgroundColor: Colors.white,
                expandedHeight: expandedHeight,
                flexibleSpace: featureParentWidget,
                pinned: true,
                floating: true,
                elevation: 179,
                bottom: PreferredSize(
                  child: sortItemWidget,
                  preferredSize: Size(double.infinity, 42),
                ),
              ),
            ),
            handle:
              NestedScrollView.sliverOverlapAbsorberHandleFor(context),
          ),
        ],
    body: body);

expandedHeight 指可以擴(kuò)展的高度

flexibleSpace 在appbar里面還可以設(shè)置彈性空間的widget,比如希望appbar伸展之后的背景是一張圖片,就可以在這里設(shè)置

pinned
appbar是否應(yīng)該保留在滾動(dòng)視圖頂部

floating
用戶(hù)向appbar滾動(dòng)時(shí),是否應(yīng)立即顯示appbar。

其他參數(shù)參考:

https://api.flutter.dev/flutter/material/SliverAppBar-class.html

各個(gè)參數(shù)的示例圖片如下:


image

TabLayout + ViewPager怎么實(shí)現(xiàn)

使用TabBar和TabBarView實(shí)現(xiàn),具體實(shí)現(xiàn)方式如下:

  • TabBar實(shí)現(xiàn)title
Widget titleBar = Container(
  height: 48,
  color: Colors.green,
  margin: EdgeInsets.only(top: 24),
  child: TabBar(
    tabs: titleArray.map((f) {
      return Text(
        f,
        style: TextStyle(color: Colors.red, fontSize: 14),
      );
    }).toList(),
    onTap: _tabClicked,
    controller: _controller,
    indicatorSize: TabBarIndicatorSize.label,
    isScrollable: false,
    indicatorColor: Colors.pink,
  ),
);
  • TabBarView實(shí)現(xiàn)
Widget contentView = Container(
    color: Colors.amber,
    child: TabBarView(
      controller: _controller,
      children: titleArray.map((f) {
        return Center(
          child: Text(
            "this is $f",
            style: TextStyle(color: Colors.red, fontSize: 24),
          ),
        );
      }).toList(),
    ));

一個(gè)實(shí)現(xiàn)了Tab標(biāo)題,一個(gè)實(shí)現(xiàn)了Tab下的具體頁(yè)面內(nèi)容,兩者產(chǎn)生關(guān)系的紐帶是_controller變量,這個(gè)變量是TabController類(lèi)型。

全部實(shí)現(xiàn)代碼如下:

class TabViewDemoWidget extends StatelessWidget {
  TabController _controller;
  var initSelectedIndex = 0;

  final titleArray = ["A", "B", "C", "D", "E"];

  _tabScrollListener() {
    if (_controller.index != initSelectedIndex) {
      //todo tab changed
    }
  }

  @override
  Widget build(BuildContext context) {
    _controller = TabController(
      initialIndex: initSelectedIndex, //初始選中頁(yè)
      length: 5, //總頁(yè)數(shù)
      vsync: ScrollableState(),
    );

    _controller.addListener(_tabScrollListener);

    Widget titleBar = Container(
      height: 48,
      color: Colors.green,
      margin: EdgeInsets.only(top: 24),
      child: TabBar(
        tabs: titleArray.map((f) {
          return Text(
            f,
            style: TextStyle(color: Colors.red, fontSize: 14),
          );
        }).toList(),
        onTap: _tabClicked,
        controller: _controller,
        indicatorSize: TabBarIndicatorSize.label,
        isScrollable: false,
        indicatorColor: Colors.pink,
      ),
    );

    Widget contentView = Container(
        color: Colors.amber,
        child: TabBarView(
          controller: _controller,
          children: titleArray.map((f) {
            return Center(
              child: Text(
                "this is $f",
                style: TextStyle(color: Colors.red, fontSize: 24),
              ),
            );
          }).toList(),
        ));
    return Scaffold(
      appBar: PreferredSize(
        child: titleBar,
        preferredSize: Size(double.infinity, 48),
      ),
      body: contentView,
    );
  }

  _tabClicked(int index) {}
}

底部導(dǎo)航欄怎么實(shí)現(xiàn)

Scaffold有一個(gè)bottomNavigationBar屬性,設(shè)置這個(gè)屬性就可以實(shí)現(xiàn),具體實(shí)現(xiàn)如下:

Scaffold(
    body: Container(),//define your own body content
    bottomNavigationBar: BottomNavigationBar(
        currentIndex: _selectedIndex,
        type: BottomNavigationBarType.fixed,
        selectedFontSize: 12,
        unselectedFontSize: 12,
        unselectedItemColor: Color.fromARGB(0XFF, 0X40, 0X40, 0X40),
        selectedItemColor: Color.fromARGB(0XFF, 0XFE, 0X3F, 0X01),
        items: [
          BottomNavigationBarItem(
              activeIcon: Container(
                width: 24,
                height: 24,
                child: Image.asset("images/main_activity_main_pressed.png"),
              ),
              icon: Container(
                width: 24,
                height: 24,
                child: Image.asset("images/main_activity_main_normal.png"),
              ),
              title: Text(
                "主頁(yè)",
              )),
          BottomNavigationBarItem(
              activeIcon: Container(
                width: 24,
                height: 24,
                child: Image.asset(
                    "images/main_activity_classify_pressed.png"),
              ),
              icon: Container(
                width: 24,
                height: 24,
                child:
                    Image.asset("images/main_activity_classify_normal.png"),
              ),
              title: Text(
                "分類(lèi)",
              )),
        ],
        onTap: onItemTaped),
  );

onTap 屬性要給一個(gè)item點(diǎn)擊的響應(yīng)事件,攜帶index參數(shù)。當(dāng)這個(gè)方法觸發(fā)之后可以做狀態(tài)改變操作。

AlertDialog怎么實(shí)現(xiàn)

flutter自身有AlertDialog Widget,但是可能不滿(mǎn)足我們的需求,可以自定義

Dialog Widget里面有一個(gè)child屬性,可以設(shè)置自己想要的對(duì)話(huà)框形式,通過(guò)showDialog方法將對(duì)話(huà)框顯示出來(lái)。

class DialogDemoWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () => _willPopScope(context),
        child: Scaffold(
          body: Center(
              child: Container(
            child: Text("show dialog demo"),
          )),
        ));
  }

  Future<bool> _willPopScope(BuildContext context) async {
    return showDialog(
            context: context,
            builder: (context) {
              //design your own dialog content
              Widget dialogChild = Container(
                width: 302,
                height: 242,
                child: Center(
                  child: Text("this is dialog"),
                ),
              );
              return Dialog(
                backgroundColor: null,
                elevation: 24,
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(24))),
                child: dialogChild,
              );
            }) ??
        false;
  }
}

ProgressDialog怎么實(shí)現(xiàn)

ProgressDialog可以通過(guò)PopupRoute實(shí)現(xiàn),他的原理是在已有的路由上面再繪制一層。

借鑒別人的實(shí)現(xiàn),加自己的改造

///加載彈框
class ProgressDialog {
  static bool _isShowing = false;

  ///展示
  static void showProgress(BuildContext context, {Widget child}) {
    if (child == null) {//define your own child
      child = Theme(
          data: Theme.of(context)
              .copyWith(accentColor: ColorUtil.hexToColor("#FFFE7501")),
          child: Stack(
            children: <Widget>[
              Center(
                child: Container(
                  width: 46,
                  height: 46,
                  child: new CircularProgressIndicator(
                    strokeWidth: 3,
                  ),
                ),
              ),
              Center(
                  child: Text(
                    "加載中",
                    style: TextStyle(
                        fontSize: 12, color: ColorUtil.hexToColor("#FF202020")),
                  )),
            ],
          ));
    }

    if (!_isShowing) {
      _isShowing = true;
      Navigator.push(
        context,
        _PopRoute(
          child: _Progress(
            child: child,
          ),
        ),
      );
    }
  }

  ///隱藏
  static void dismiss(BuildContext context) {
    if (context == null) {
      return;
    }
    if (_isShowing) {
      Navigator.of(context).pop();
      _isShowing = false;
    }
  }
}

///Widget
class _Progress extends StatelessWidget {
  final Widget child;

  _Progress({
    Key key,
    @required this.child,
  })  : assert(child != null),
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
        color: Colors.transparent,
        child: Center(
          child: child,
        ));
  }
}

///Route
class _PopRoute extends PopupRoute {
  final Duration _duration = Duration(milliseconds: 300);
  Widget child;

  _PopRoute({@required this.child});

  @override
  Color get barrierColor => null;

  @override
  bool get barrierDismissible => true;

  @override
  String get barrierLabel => null;

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return child;
  }

  @override
  Duration get transitionDuration => _duration;
}

點(diǎn)擊控件之后怎么響應(yīng)事件更新視圖

Widget從大體上可以分為StatelessWidget和StatefullWidget,其中StatefullWidget可以根據(jù)setState方法觸發(fā)對(duì)整個(gè)視圖的刷新。

粗略地,StatefullWidget的生命周期可以分為initState,build,dispose。

在調(diào)用了setState方法之后,會(huì)觸發(fā)build方法使子widget重新構(gòu)建。

方法如下:

class SetStateDemoWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return SetStateDemoWidgetState();
  }
}

class SetStateDemoWidgetState extends State<SetStateDemoWidget> {
  var index = 0;

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

  @override
  Widget build(BuildContext context) {
    Widget numberText = Text(
      "$index",
      style: TextStyle(fontSize: 18, color: Colors.cyan),
    );
    Widget addButton = Container(
      margin: EdgeInsets.only(top: 16),
      child: FlatButton(
        onPressed: _buttonClicked,
        child: Icon(
          Icons.add,
          size: 36,
        ),
      ),
    );

    return Scaffold(
      body: Container(
        width: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            numberText,
            addButton,
          ],
        ),
      ),
    );
  }

  _buttonClicked() {
    setState(() {
      ++index;
    });
  }
}

在_buttonClicked方法響應(yīng)了點(diǎn)擊事件之后,再調(diào)用setState方法將index自增,此時(shí)會(huì)觸發(fā)build重新渲染view tree.

InheritedWidget怎么用

InheritedWidget用來(lái)解決父Widget的數(shù)據(jù)變化時(shí)通知子Widget。

具體用法是,父Widget繼承自InheritedWidget,并定義一個(gè)static方法用來(lái)對(duì)外提供對(duì)象實(shí)例,另外有一個(gè)child屬性用于設(shè)置子Widget,還要設(shè)置數(shù)據(jù),用于給這個(gè)子widget引用。同時(shí)覆寫(xiě)是否刷新數(shù)據(jù)的方法。當(dāng)數(shù)據(jù)變化時(shí),子widget就收到通知了。使用方法如下:

///先繼承InheritedWidget
class InheritedData extends InheritedWidget {
  final String data;//用于給子Widget使用

  InheritedData({
    this.data,
    Widget child,//子Widget
  }) : super(child: child);
  //提供static方法給外部使用
  static InheritedData of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<InheritedData>();
  }
  //判斷是否通知子Widget
  @override
  bool updateShouldNotify(InheritedData old) => true;
}

///子Widget定義
class TestInheritedDataWidget extends StatefulWidget {
  @override
  _TestInheritedDataWidgetState createState() =>
      _TestInheritedDataWidgetState();
}

class _TestInheritedDataWidgetState extends State<TestInheritedDataWidget> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(
      //引用父Widget的數(shù)據(jù)
        "${InheritedData.of(context).data}",
        style: TextStyle(fontSize: 18, color: Colors.pink),
      ),
    );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    //收到通知
    print("didChangeDependencies invoked");
  }
}

class ParentWidget extends StatefulWidget {
  @override
  _ParentWidgetState createState() => _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  var data = "you are beautiful";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        child: Container(
          color: Colors.cyan,
          width: double.infinity,
          child: InheritedData(
            data: data,
            child: TestInheritedDataWidget(),
          ),
        ),
        onTap: _buttonClicked,
      ),
    );
  }

  _buttonClicked() {
    setState(() {
    //點(diǎn)擊按鈕之后數(shù)據(jù)發(fā)生變化
      data = "in white";
    });
  }
}

LinearLayout的sumWeight以及單個(gè)child的weight怎么實(shí)現(xiàn)

用Expanded Widget可以實(shí)現(xiàn)這種效果。源碼里面針對(duì)Expanded的注釋是它作為Row,Column,F(xiàn)lex的子Widget,里面可以含有多個(gè)子Widget,并且每個(gè)子widget通過(guò)flex來(lái)分配剩余的空間。

用下面這個(gè)例子說(shuō)明:

class FlexWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Expanded(
              child: Container(
                color: Colors.pink,
              ),
              flex: 1,
            ),
            Expanded(
              child: Container(
                color: Colors.lightGreenAccent,
              ),
              flex: 2,
            ),
          ],
        ),
      ),
    );
  }
}

運(yùn)行下看效果可以知道,粉色占據(jù)了三分之一,淺綠色占據(jù)了三分之二的空間。

視圖比較復(fù)雜,寫(xiě)的代碼比較長(zhǎng),導(dǎo)致代碼結(jié)尾有海量的反括號(hào),怎么優(yōu)化

還是以上面實(shí)現(xiàn)weight效果的代碼做示例,可以看到代碼后邊有9個(gè)反括號(hào),看起來(lái)比較累,容易造成心理壓力。

class FlexWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var child1 = Expanded(
      child: Container(
        color: Colors.pink,
      ),
      flex: 1,
    );

    var child2 = Expanded(
      child: Container(
        color: Colors.lightGreenAccent,
      ),
      flex: 2,
    );

    var child3 = Row(
      mainAxisAlignment: MainAxisAlignment.center,
      mainAxisSize: MainAxisSize.max,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        child1,
        child2,
      ],
    );

    var child4 = Container(
      width: double.infinity,
      child: child3,
    );

    return Scaffold(
      body: child4,
    );
  }
}

把每個(gè)child拆出來(lái)作為一個(gè)widget賦值給一個(gè)變量,這樣就可以將一些小的邏輯分出來(lái),避免每個(gè)子widget的業(yè)務(wù)邏輯堆積在一起,使得邏輯看起來(lái)比較清晰。

FrameLayout怎么實(shí)現(xiàn)

Stack配合Positioned使用,可以實(shí)現(xiàn)FrameLayout的效果。

class StackDemoWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var child = Stack(
      children: <Widget>[
        Container(
          width: 480,
          height: 480,
          color: Colors.pink,
        ),
        Positioned(
          child: Container(
            width: 360,
            height: 360,
            color: Colors.amber,
          ),
          top: 84,
          bottom: 84,
        ),
        Positioned(
          child: Container(
            width: 240,
            height: 240,
            color: Colors.deepOrange,
          ),
          right: 12,
          left: 12,
        )
      ],
    );

    var child1 = Center(
      child: Container(
        child: child,
        width: 480,
        height: 480,
      ),
    );
    return Scaffold(
      body: child1,
    );
  }
}

Positioned的左右上下屬性是相對(duì)于Stack邊緣的偏移,如果設(shè)置左右或上下會(huì)影響到Positioned的寬高。

數(shù)據(jù)處理篇

Android的SharePreference在這里怎么用

在工程下的pubspec.yaml文件中添加引用:

dependencies:
  shared_preferences: ^0.5.6

然后在命令行執(zhí)行:

flutter pub get

然后在代碼中就可以使用SharePreference的功能了。flutter中的SharePreference跟Android里面的一樣,可能也會(huì)阻塞UI線(xiàn)程,需要使用async修飾相關(guān)方法。使用舉例:

import 'package:shared_preferences/shared_preferences.dart';

class SharedPreferenceUtil {
  static SharedPreferences _prefs;

  SharedPreferenceUtil._privateConstructor();

  static final SharedPreferenceUtil instance =
      SharedPreferenceUtil._privateConstructor();

  Future<SharedPreferences> get prefs async {
    if (_prefs != null) return _prefs;
    _prefs = await SharedPreferences.getInstance();
    return prefs;
  }

  static const String KEY_SEARCH_HISTORY = "search_history";
  static const String KEY_USER_TOKEN = "token";

  void setValue(String key, String value) async {
    SharedPreferences sharedPreferences = await instance.prefs;
    sharedPreferences.setString(key, value);
  }

  Future<String> getValue(String key) async {
    SharedPreferences sharedPreferences = await instance.prefs;
    return sharedPreferences.getString(key);
  }
}

在這里我們把SharedPreferences抽象出來(lái),做一個(gè)單例對(duì)外提供。所有的set和get必須用async修飾,因?yàn)樗亲枞降?。調(diào)用的地方舉例:

SharedPreferenceUtil.instance
    .getValue(SharedPreferenceUtil.KEY_USER_TOKEN)
    .then((value) {
  //do something
});

這里getValue之后,然后調(diào)用then方法,意思是執(zhí)行完了,在then方法里面獲取到返回的值,可以做接下來(lái)的操作了。

Android的數(shù)據(jù)庫(kù)怎么用

在工程下的pubspec.yaml文件中添加引用:

dependencies:
  sqflite: ^1.1.7+3

然后在命令行執(zhí)行:

flutter pub get

然后再代碼中就可以使用數(shù)據(jù)庫(kù)的相關(guān)功能了。

使用示例:

import 'package:flutter_hello/database/user_info_impl.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DataBaseHelper {
  static Database _database;

  static final _databaseName = "coupon.db";
  static final _databaseVersion = 1;

  static const String _CREATE_TABLE = "CREATE TABLE IF NOT EXISTS ";

  DataBaseHelper._privateConstructor();

  static final DataBaseHelper instance = DataBaseHelper._privateConstructor();

  Future<Database> get database async {
    if (_database != null) return _database;
    _database = await _initDatabase();
    return _database;
  }

  _initDatabase() async {
    String path = join(await getDatabasesPath(), _databaseName);
    return await openDatabase(path,
        version: _databaseVersion, onCreate: _onCreate);
  }

  Future _onCreate(Database db, int version) async {
    await db.execute(_CREATE_TABLE +
        UserInfoImpl.TABLE_USER_INFO +
        UserInfoImpl.generateCreateSql());
  }

  Future<int> insert(String dbName, Map<String, dynamic> data) async {
    Database db = await instance.database;
    return db.insert(
      dbName,
      data,
    );
  }

  Future<List<Map<String, dynamic>>> query(String dbName) async {
    Database db = await instance.database;
    final List<Map<String, dynamic>> maps = await db.query(dbName);
    return maps;
  }

  Future<void> update(String tableName, Map<String, dynamic> data, String keyId,
      String equalValue) async {
    Database db = await instance.database;
    await db.update(
      tableName,
      data,
      where: "$keyId = ?",
      whereArgs: [equalValue],
    );
  }

  Future<void> delete(String tableName, String keyId, String equalValue) async {
    Database db = await instance.database;
    await db.delete(
      tableName,
      where: "$keyId = ?",
      whereArgs: [equalValue],
    );
  }
}

這是一個(gè)數(shù)據(jù)庫(kù)操作的類(lèi),將增刪改查抽象出來(lái),做具體的操作。在做操作之前獲取數(shù)據(jù)庫(kù)操作句柄database,其實(shí)他也是一個(gè)單例,使用了單例模式。

具體操作類(lèi)實(shí)現(xiàn)之后,如果我們要操作具體的某個(gè)表就比較方便了。比如針對(duì)user_info這個(gè)表的操作類(lèi)UserInfoImpl,我們可以這樣操作:

insertUserInfo(UserInfoBean userInfoBean) {
    DataBaseHelper.instance.insert(TABLE_USER_INFO, userInfoBean.toJson());
}

Future<UserInfoBean> getUserInfo() async {
    List<Map<String, dynamic>> lists =
        await DataBaseHelper.instance.query(TABLE_USER_INFO);
    if (lists != null && lists.length > 0) {
      return UserInfoBean.fromJson(lists[0]);
    }
    return null;
}

deleteUserInfo(String userId) {
    DataBaseHelper.instance.delete(TABLE_USER_INFO, "id", userId);
}

updateUserInfo(UserInfoBean bean) {
    DataBaseHelper.instance
        .update(TABLE_USER_INFO, bean.toJson(), "id", bean.id.toString());
}

Json數(shù)據(jù)怎么處理

在工程下的pubspec.yaml文件中添加引用:

//庫(kù)版本可能已經(jīng)更新,可以在https://pub.dev/packages/網(wǎng)站搜索最新的版本
dev_dependencies:
  build_runner: ^1.0.0
  json_serializable: ^2.0.0

然后在命令行執(zhí)行:

flutter pub get

接下來(lái)就可以處理json數(shù)據(jù)了。處理json數(shù)據(jù)主要分三個(gè)步驟:

  • 根據(jù)網(wǎng)絡(luò)請(qǐng)求的字段,定義對(duì)應(yīng)的類(lèi)及屬性字段
  • 在類(lèi)中添加序列化和反序列化接口
  • 通過(guò)flutter指令生成對(duì)應(yīng)的賦值處理

用以下json數(shù)據(jù)舉例說(shuō)明:

{
    "total_count":12,
    "total_page":1,
    "page":1,
    "data":[]
}

首先定義類(lèi)及屬性字段,文件名是withdraw_detail_bean.dart

import 'package:json_annotation/json_annotation.dart';

part 'withdraw_detail_bean.g.dart';

@JsonSerializable()
class WithdrawDetailBean {
  WithdrawDetailBean(this.data, this.totalPage, this.totalCount, this.page);

  @JsonKey(name: "total_count")
  int totalCount;
  @JsonKey(name: "total_page")
  int totalPage;
  int page;
  List<WithDrawItemBean> data;

  factory WithdrawDetailBean.fromJson(Map<String, dynamic> json) =>
      _$WithdrawDetailBeanFromJson(json);

  Map<String, dynamic> toJson() => _$WithdrawDetailBeanToJson(this);
}

首先要添加part

'withdraw_detail_bean.g.dart',因?yàn)閜art關(guān)鍵字可以幫助創(chuàng)建一個(gè)模塊化的,可共享的代碼庫(kù)。后面執(zhí)行指令的時(shí)候可以生成一個(gè)withdraw_detail_bean.g.dart文件,里面包含了當(dāng)前數(shù)據(jù)序列化相關(guān)的處理代碼。

其次在定義的類(lèi)前面添加JsonSerializable注解。

定義構(gòu)造函數(shù),定義與返回?cái)?shù)據(jù)對(duì)應(yīng)的key,通過(guò)JsonKey注解,可以簡(jiǎn)化key對(duì)應(yīng)的變量命名。

定義序列化和反序列化的接口,用于外部調(diào)用

最后一步就是執(zhí)行生成處理json的代碼,用指令實(shí)現(xiàn),分兩種。

一種是一次生成,后面再有修改的話(huà),再執(zhí)行,再生成:

flutter packages pub run build_runner build

另外一種是持續(xù)生成,一旦修改了json定義類(lèi),就會(huì)馬上自動(dòng)生成對(duì)應(yīng)的處理類(lèi):

flutter packages pub run build_runner watch

最后可以看到data數(shù)組里面定義了一個(gè)WithDrawItemBean類(lèi),同樣的WithDrawItemBean類(lèi),需要再像上面這樣定義一遍就可以了。

網(wǎng)絡(luò)請(qǐng)求

網(wǎng)絡(luò)請(qǐng)求一般借助現(xiàn)有的庫(kù)實(shí)現(xiàn),http庫(kù)對(duì)于各種方式的網(wǎng)絡(luò)請(qǐng)求支持比較好,網(wǎng)址是:https://pub.dev/packages/http。

get請(qǐng)求

這里以最復(fù)雜的情況做例子,query + header:

Future<NetResponseBean> _getResponse(
      String baseUrl, String api, Map<String, String> queryMap) async {
    var _client = http.Client();
    if (!api.contains("?")) {
      api = api + "?";
    }
    try {
      var url = baseUrl + api + _getQuery(queryMap);
    
      Map<String, String> headers = Map();
      _getCommonHeaders(headers);
      http.Response response = await _client.get(url, headers: headers);
      if (response.statusCode == HttpStatus.ok) {
        var body = response.body;
        Map<String, dynamic> data = jsonDecode(body);
        NetResponseBean responseData = NetResponseBean.fromJson(data);
        if (responseData != null) {
          return responseData;
        }
      }
    } catch (exception, stackTrace) {
      print("_getResponse stackTrace:$stackTrace");
    } finally {
      if (_client != null) {
        _client.close();
      }
    }
    return null;
}

第一步,獲取client對(duì)象,這個(gè)對(duì)象在finally里面必須關(guān)掉,跟Android的操作是一樣的。

第二步,拼接query到url中。

第三步,填充header到一個(gè)Map集合中。

這幾步走完了調(diào)用對(duì)應(yīng)的接口,填充對(duì)應(yīng)的參數(shù)就可以了。

檢查返回碼,ok的話(huà),獲取body數(shù)據(jù),轉(zhuǎn)換成json格式,然后用對(duì)應(yīng)json類(lèi)序列化就可以使用返回的數(shù)據(jù)了。

post請(qǐng)求

這里以最復(fù)雜的情況舉例,header + request body

Future<NetResponseBean> _getPostResponse(
      String api, Map<String, String> parameters) async {
    var _client = http.Client();
    var url = _BAE_URL + api;
    try {
      //設(shè)置header
      Map<String, String> headersMap = new Map();
      _getCommonHeaders(headersMap);
      http.Response response = await _client.post(url,
          headers: headersMap, body: parameters, encoding: Utf8Codec());
      if (response.statusCode == 200) {
        String bodyData = response.body;
        if (bodyData != null) {
          Map<String, dynamic> data = jsonDecode(bodyData);
          NetResponseBean response = NetResponseBean.fromJson(data);
          return response;
        }
      } else {
        print('_getPostResponse error');
      }
    } catch (exception) {
      print("_getPostResponse fail:" + exception.toString());
    } finally {
      if (_client != null) {
        _client.close();
      }
    }
    return null;
}

跟上面get請(qǐng)求的流程差別不大,主要是接口調(diào)用不同,另外需要注意的是這里body是dynamic類(lèi)型,傳的是Map集合。當(dāng)然也可以傳json字符串,一個(gè)常見(jiàn)的場(chǎng)景是bean類(lèi)轉(zhuǎn)化為json,然后傳遞,對(duì)應(yīng)的處理是:

var body = json.encode(jsonBean);

上傳

Future requestUploadFile(File file, Function callBack) async {
    var url = _URL + "your sub url";
    var client = http.MultipartRequest("post", Uri.parse(url));
    http.MultipartFile.fromPath(
      'file',
      file.path,
    ).then((http.MultipartFile file) {
      _getOSCommonHeaders(client.headers);
      client.files.add(file);
      client.fields["description"] = "descriptiondescription";
      client.send().then((http.StreamedResponse response) {
        if (response.statusCode == 200) {
          response.stream.transform(utf8.decoder).join().then((String string) {
            print("requestUploadFile:$string");
            Map<String, dynamic> data = jsonDecode(string);
            if (data != null && data.length > 0) {
              NetResponseBean uploadResponse = NetResponseBean.fromJson(data);
              if (uploadResponse != null) {
                if (uploadResponse.code == 0) {
                  UploadImageResultBean uploadImageResultBean =
                      UploadImageResultBean.fromJson(uploadResponse.data);
                  callBack(uploadImageResultBean.fileUrl, 0);
                } else {
                  callBack("", uploadResponse.code);
                }
              }
            }
          });
        }
      }).catchError((error) {
        print("requestUploadFile error:$error");
      });
    });
  }

代碼如上,一般性的上傳操作。

下載

Future<File> _downloadFile(String url, String filename) async {
    http.Client _client = new http.Client();
    try {
      var req = await _client.get(Uri.parse(url));
      var bytes = req.bodyBytes;
      String dir = (await getApplicationDocumentsDirectory()).path;
      File file = new File('$dir/$filename');
      await file.writeAsBytes(bytes);
      return file;
    } finally {
      _client.close();
    }
}

上面是比較簡(jiǎn)單的下載,下面從別處抄一個(gè)帶進(jìn)度的:

https://gist.github.com/ajmaln/c591cfb71d66bb6e688fe7027cbbe606

import 'dart:typed_data';
import 'dart:io';

import 'package:http/http.dart';
import 'package:path_provider/path_provider.dart';


downloadFile(String url, {String filename}) async {
  var httpClient = http.Client();
  var request = new http.Request('GET', Uri.parse(url));
  var response = httpClient.send(request);
  String dir = (await getApplicationDocumentsDirectory()).path;
  
  List<List<int>> chunks = new List();
  int downloaded = 0;
  
  response.asStream().listen((http.StreamedResponse r) {
    
    r.stream.listen((List<int> chunk) {
      // Display percentage of completion
      debugPrint('downloadPercentage: ${downloaded / r.contentLength * 100}');
      
      chunks.add(chunk);
      downloaded += chunk.length;
    }, onDone: () async {
      // Display percentage of completion
      debugPrint('downloadPercentage: ${downloaded / r.contentLength * 100}');
      
      // Save the file
      File file = new File('$dir/$filename');
      final Uint8List bytes = Uint8List(r.ntentLength);
      int offset = 0;
      for (List<int> chunk in chunks) {
        bytes.setRange(offset, offset + chunk.length, chunk);
        offset += chunk.length;
      }
      await file.writeAsBytes(bytes);   
      return;       
   });
}

公眾號(hào):


微信公眾號(hào)二維碼.jpg
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過(guò)簡(jiǎn)信或評(píng)論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

  • Flutter是Google開(kāi)發(fā)的一套全新的跨平臺(tái)、開(kāi)源UI框架(本質(zhì)上就是sdk)。 支持iOS、Android...
    HarveyLegend閱讀 8,588評(píng)論 1 42
  • 今天開(kāi)始,我要努力了。 明天開(kāi)始,我要背單詞了。 這頓之后,我要開(kāi)始減肥了。 改變的決心下了無(wú)數(shù)個(gè),卻一次都沒(méi)開(kāi)始...
    思遠(yuǎn)舟閱讀 589評(píng)論 0 0
  • 春天漸逝,夏天悄來(lái)!又到了露肉的季節(jié)!發(fā)福利的時(shí)候到了!剛才在場(chǎng)內(nèi)遇一小美女!穿一黃色套裙,外層是一紗窗,內(nèi)層是一...
    那一見(jiàn)的風(fēng)情521閱讀 177評(píng)論 0 1
  • 之前不小心把JAVA分類(lèi)寫(xiě)成了java發(fā)布了,然后又改了回來(lái),并且手動(dòng)地在博客public/categories/...
    vzardlloo閱讀 879評(píng)論 0 1
  • 這兩天是和財(cái)富相關(guān)的時(shí)間,好朋友讓我?guī)退龁?wèn)一下財(cái)富! 不用說(shuō),這個(gè)問(wèn)題自然要幫忙的。 和她做完簡(jiǎn)...
    郗紅嘉閱讀 238評(píng)論 1 3

友情鏈接更多精彩內(nèi)容