flutter小问题总结

2021-01-05  本文已影响0人  woniu

1、padding和margin

padding: EdgeInsets.fromLTRB(10, 10, 15, 20),//内边距,里边的蓝块,需要给宽高
margin: EdgeInsets.fromLTRB(100, 10, 15, 15),//外边距,父容器本身相对外部容器的移动

2、flutter的key

Key有两个重要的子类:LocalKey 和 GlobalKey,而他们各自也有不同的子类实现。

3、流式布局:GridView、Wrap、flow

GridView详解

4、flutter添加所有的图片

5、flutter自定义方法和控件

5.1 自定义方法
void _getGuessLicktData() async {
    var url = "https://a4cj1hm5.api.lncld.net/1.1/classes/shopGuessLike";
    await HttpRequest.request(url).then((value) {
      print(value);
      var list = new GHGuessLikeModel.fromJson(value).results;
      setState(() {
        this._getGuessLikeList = list;
      });
    });
  }
或者
  void getBatteryInfo() async{
    final int result = await platform.invokeMethod("getBatteryInfo");
    setState(){
      _result = result;
    };
  }
5.2 自定义控件
  Widget _swiperWidget() {
    if (this._carouselDataList.length == 0) {
      return LoadingWidget();
    }
    return Container(
      height: ScreenAdaper.height(400),
      width: double.infinity,
      child: Swiper(
          itemBuilder: (BuildContext context, int index) {
            GHomeCarouselDataItemModel carouselModel = this._carouselDataList[index];
            return GestureDetector(
              onTap: () {},
              child: Image.network(
                carouselModel.url, // pic
                fit: BoxFit.fill,
              ),
            );
          },
          itemCount: this._carouselDataList.length,
          pagination: new SwiperPagination(),
          autoplay: true
      ),
    );
  }

6、MethodChannel和EventChannel
MethodChannel用通俗的语言来描述它的作用就是,当你像在flutter端调用native功能的时候,可以用它。
EventChannel用通俗的语言来描述就是,当native想通知flutter层一些消息的时候,可以用它。

7、跨组件事件
在组件之间如果有事件需要传递,一方面可以一层层来传递,另一方面我们也可以使用一个EventBus工具来完成。

dependencies:
  event_bus:^1.1.1

7.1 定义在组件之间传递的对象

class UserInfo {
  String nickname;
  int age;  
  UserInfo(this.nickname, this.age);
}

7.2 创建一个💰uanjud额EventBus对象:

final eventBus = EventBus();

7.3 在选定的Widget中,发送事件

class ZHButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text("ZHButton"),
      onPressed: () {
        final info = UserInfo("why", 18);
        eventBus.fire(info);
      },
    );
  }
}

7.4 在接收的Widgt中,监听事件

class ZHText extends StatefulWidget {
  @override
  _ZHTextState createState() => _ZHTextState();
}

class _ZHTextState extends State<ZHText> {
  String message = "Hello!";

  @override
  void initState() {
    super.initState();
//监听数据,然后刷新
    eventBus.on<UserInfo>().listen((data) {
      setState(() {
        message = "${data.nickname}-${data.level}";
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text(message, style: TextStyle(fontSize: 30),);
  }
}
上一篇下一篇

猜你喜欢

热点阅读