继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

关于Flutter中的StatefulWidget小优化

慕仰1870381
关注TA
已关注
手记 53
粉丝 4484
获赞 456

Flutter中使用StatefulWidget非常苦逼,写一个类继承StatefulWidget,还要写一个类继承State,大多数都是模板代码,我整理过一个代码模板,但是总感觉不是很爽。有没有更简洁的方式?于是我就想改造一下StatefulWidget,让开发起来更简洁。

这里只有一个类,取名叫做usefulStatefulWidget,意思是对于使用StatefulWidget很有帮助,然后利用Dart类里面的extends和with的特性,把StatefulWidget和State这两个类做了一些封装,具体代码如下:

abstract class usefulStatefulWidget extends _Stateful with State<StatefulWidget> {
  @override
  State<StatefulWidget> createState() => this;

  refresh() => setState(() {});
}

abstract class _Stateful extends StatefulWidget {}

这样一来,我们写代码就简洁多了,不再需要去写那么多类了。例如,我们就把创建Flutter项目时,给我们提供的示例代码改造一下,如下:

import 'package:flutter/material.dart';
import 'package:demo/usefulStatefulWidget.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '简单实用的StatefulWidget',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: '简单实用的StatefulWidget'),
    );
  }
}

class MyHomePage extends usefulStatefulWidget {
  MyHomePage({Key key, this.title});

  final String title;
  int _counter = 0;

  void _incrementCounter() {
    _counter++;
    refresh();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              'You have pushed the button this many times:',
            ),
            new Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ),
    );
  }
}

这样一来就节省了一些代码,写起来也方便多了。

注意:如果需要使用到大量的state或者交互状态需要更改,这种封装其实没有多大作用,因为我们要调用setState,封装的代码里面并没有做任何处理。这里只是提供了一种优化方式,仅供参考。


我是阿韦,专注于Flutter研究,更多Flutter学习干货可以看我的github: https://github.com/AweiLoveAndroid/Flutter-learning 欢迎大家关注。

打开App,阅读手记
2人推荐
发表评论
随时随地看视频慕课网APP