Flutter 代码优化相关问题

482 阅读1分钟

1. 尽可能的使用 const

x = Container();
y = Container();
x == y // false

x = const Container();
y = const Container();
x == y // true

解释:

代码中我们可以看到同一个组件在const的时候,内存中可以被重复利用,这样可以更好的帮我们节省内存空间。

2. 尽可能使用 const 构造方法

class CustomWidget extends StatelessWidget {
 const CustomWidget();
 @override
  Widget build(BuildContext context) {
    ...
  }
}

解释

当构建组件时,仅重建应该更新的小部件。

3 使用 nil 代替 const Container()

// 常用的方法
text != null ? Text(text) : const Container() 

// 更好的方法
text != null ? Text(text) : const SizedBox() 

// 最好的方法
text != null ? Text(text) : nil
or
if (text != null) Text(text)

解释: nil 在使用的时候几乎没有任何的开销 详细解释请看(pub.dev/packages/ni…)

4 长列表中 listview 尽可能使用itemExtent。

解释:

这有助于 Flutter 计算 ListView 滚动位置,而不是计算每个小部件的高度

5. 避免使用 AnimationController with setState

void initState () {
 _controller = AnimationController (
 vsync: this,
    duration: Duration ( seconds: 1 ) ,
  )
 ..addListener (() => setState (() {}))  ;
 } Column (
 children: [
 Placeholder () , // rebuilds
    Placeholder () , // rebuilds
    Placeholder () , // rebuilds
    Transform.translate (  // rebuilds
 offset: Offset ( 100 * _controller.value, 0 ) ,
      child: Placeholder () ,
    ) , 
  ] ,
 ) ,

优化后

void initState () {
 _controller = AnimationController (
 vsync: this,
    duration: Duration ( seconds: 1 ) ,
  ); 
 // No  addListener(...)
 } AnimatedBuilder (
 animation: _controller,
  builder: ( _, child ) {  
 return Transform.translate (
 offset: Offset ( 100 * _controller.value, 0 ) ,
      child: child,
    ) ;
  } , 
  child: Placeholder () ,
  ) , 

解释: setState后需要重新构建整个UI,而不是单独的animation widget 更新。

6.使用Listview的时候 item 包含 image 的性能优化

ListView.builder(
  ...
  addAutomaticKeepAlives: false (true by default)
  addRepaintBoundaries: false (true by default)
);

解释: Listview 在item 滑动到不可见的时候是不能 kill its item的,如果item中有很多高像素的图片的时候,将要消耗非常多的内存资源。

通过设置false,可能导致更多的GPU和CPU处理,但是它可以解决图片占用过多内存的问题。