
微信交流群
老孟导读:今天分享 StackOverflow 上高访问量的 20 大问题,这些问题给我一种特别熟悉的感觉,我想你一定或多或少的遇到过,有的问题在 stackoverflow 上有几十万的阅读量,说明很多人都遇到了这些问题,把这些问题整理分享给大家,每期 20 个,每隔 2 周分享一次。
# 如何避免 FutureBuilder 频繁执行future
方法
错误用法:
build(BuildContext context) {
return FutureBuilder(
future: httpCall(),
builder: (context, snapshot) {
},
);
}
Widget
2
3
4
5
6
7
8
9
正确用法:
class _ExampleState extends State<Example> {
Future<int> future;
void initState() {
future = Future.value(42);
super.initState();
}
Widget build(BuildContext context) {
return FutureBuilder(
future: future,
builder: (context, snapshot) {
},
);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 底部导航切换导致重建问题
在使用底部导航时经常会使用如下写法:
Widget _currentBody;
Widget build(BuildContext context) {
return Scaffold(
body: _currentBody,
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
...
],
onTap: (index) {
_bottomNavigationChange(index);
},
),
);
}
_bottomNavigationChange(int index) {
switch (index) {
case 0:
_currentBody = OnePage();
break;
case 1:
_currentBody = TwoPage();
break;
case 2:
_currentBody = ThreePage();
break;
}
setState(() {});
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
此用法导致每次切换时都会重建页面。
解决办法,使用IndexedStack
:
int _currIndex;
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: _currIndex,
children: <Widget>[OnePage(), TwoPage(), ThreePage()],
),
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
...
],
onTap: (index) {
_bottomNavigationChange(index);
},
),
);
}
_bottomNavigationChange(int index) {
setState(() {
_currIndex = index;
});
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# TabBar 切换导致重建(build)问题
通常情况下,使用 TabBarView 如下:
TabBarView(
controller: this._tabController,
children: <Widget>[
_buildTabView1(),
_buildTabView2(),
],
)
2
3
4
5
6
7
此时切换 tab 时,页面会重建,解决方法设置PageStorageKey
:
var _newsKey = PageStorageKey('news');
var _technologyKey = PageStorageKey('technology');
TabBarView(
controller: this._tabController,
children: <Widget>[
_buildTabView1(_newsKey),
_buildTabView2(_technologyKey),
],
)
2
3
4
5
6
7
8
9
10
# Stack 子组件设置了宽高不起作用
在 Stack 中设置 100x100 红色盒子,如下:
Center(
child: Container(
height: 300,
width: 300,
color: Colors.blue,
child: Stack(
children: <Widget>[
Positioned.fill(
child: Container(
height: 100,
width: 100,
color: Colors.red,
),
)
],
),
),
)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
此时红色盒子充满父组件,解决办法,给红色盒子组件包裹 Center、Align 或者 UnconstrainedBox,代码如下:
Positioned.fill(
child: Align(
child: Container(
height: 100,
width: 100,
color: Colors.red,
),
),
)
2
3
4
5
6
7
8
9
# 如何在 State 类中获取 StatefulWidget 控件的属性
class Test extends StatefulWidget {
Test({this.data});
final int data;
State<StatefulWidget> createState() => _TestState();
}
class _TestState extends State<Test>{
}
2
3
4
5
6
7
8
9
10
如下,如何在_TestState 获取到 Test 的data
数据呢:
- 在_TestState 也定义同样的参数,此方式比较麻烦,不推荐。
- 直接使用
widget.data
(推荐)。
# default value of optional parameter must be constant
上面的异常在类构造函数的时候会经常遇见,如下面的代码就会出现此异常:
class BarrageItem extends StatefulWidget {
BarrageItem(
{ this.text,
this.duration = Duration(seconds: 3)});
2
3
4
异常信息提示:可选参数必须为常量,修改如下:
const Duration _kDuration = Duration(seconds: 3);
class BarrageItem extends StatefulWidget {
BarrageItem(
{this.text,
this.duration = _kDuration});
2
3
4
5
6
定义一个常量,Dart
中常量通常使用k
开头,_
表示私有,只能在当前包内使用,别问我为什么如此命名,问就是源代码中就是如此命名的。
# 如何移除 debug 模式下右上角“DEBUG”标识
MaterialApp(
debugShowCheckedModeBanner: false
)
2
3
# 如何使用 16 进制的颜色值
下面的用法是无法显示颜色的:
Color(0xb74093)
因为 Color 的构造函数是ARGB
,所以需要加上透明度,正确用法:
Color(0xFFb74093)
FF
表示完全不透明。
# 如何改变应用程序的 icon 和名称
链接:https://blog.csdn.net/mengks1987/article/details/95306508
# 如何给 TextField 设置初始值
class _FooState extends State<Foo> {
TextEditingController _controller;
void initState() {
super.initState();
_controller = new TextEditingController(text: '初始值');
}
Widget build(BuildContext context) {
return TextField(
controller: _controller,
);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Scaffold.of() called with a context that does not contain a Scaffold
Scaffold.of()中的 context 没有包含在 Scaffold 中,如下代码就会报此异常:
class HomePage extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('老孟'),
),
body: Center(
child: RaisedButton(
color: Colors.pink,
textColor: Colors.white,
onPressed: _displaySnackBar(context),
child: Text('show SnackBar'),
),
),
);
}
}
_displaySnackBar(BuildContext context) {
final snackBar = SnackBar(content: Text('老孟'));
Scaffold.of(context).showSnackBar(snackBar);
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
注意此时的 context 是 HomePage 的,HomePage 并没有包含在 Scaffold 中,所以并不是调用在 Scaffold 中就可以,而是看 context,修改如下:
_scaffoldKey.currentState.showSnackBar(snackbar);
或者:
Scaffold(
appBar: AppBar(
title: Text('老孟'),
),
body: Builder(
builder: (context) =>
Center(
child: RaisedButton(
color: Colors.pink,
textColor: Colors.white,
onPressed: () => _displaySnackBar(context),
child: Text('老孟'),
),
),
),
);
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Waiting for another flutter command to release the startup lock
在执行flutter
命令时经常遇到上面的问题,
解决办法一:
1、Mac 或者 Linux 在终端执行如下命令:
killall -9 dart
2、Window 执行如下命令:
taskkill /F /IM dart.exe
解决办法二:
删除 flutter SDK 的目录下/bin/cache/lockfile
文件。
# 无法调用setState
不能在 StatelessWidget 控件中调用了,需要在 StatefulWidget 中调用。
# 设置当前控件大小为父控件大小的百分比
1、使用FractionallySizedBox
控件
2、获取父控件的大小并乘以百分比:
MediaQuery.of(context).size.width * 0.5
# Row 直接包裹 TextField 异常:BoxConstraints forces an infinite width
解决方法:
Row(
children: <Widget>[
Flexible(
child: new TextField(),
),
],
),
2
3
4
5
6
7
# TextField 动态获取焦点和失去焦点
获取焦点:
FocusScope.of(context).requestFocus(_focusNode);
_focusNode
为 TextField 的 focusNode:
_focusNode = FocusNode();
TextField(
focusNode: _focusNode,
...
)
2
3
4
5
6
失去焦点:
_focusNode.unfocus();
# 如何判断当前平台
import 'dart:io' show Platform;
if (Platform.isAndroid) {
// Android-specific code
} else if (Platform.isIOS) {
// iOS-specific code
}
2
3
4
5
6
7
平台类型包括:
Platform.isAndroid
Platform.isFuchsia
Platform.isIOS
Platform.isLinux
Platform.isMacOS
Platform.isWindows
2
3
4
5
6
# 如何实现 Android 平台的 wrap_content 和 match_parent
你可以按照如下方式实现:
1、Width = Wrap_content Height=Wrap_content:
Wrap(
children: <Widget>[your_child])
2
2、Width = Match_parent Height=Match_parent:
Container(
height: double.infinity,
width: double.infinity,child:your_child)
2
3
3、Width = Match_parent ,Height = Wrap_conten:
Row(
mainAxisSize: MainAxisSize.max,
children: <Widget>[*your_child*],
);
2
3
4
4、Width = Wrap_content ,Height = Match_parent:
Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[your_child],
);
2
3
4
# Android 无法访问 http
其实这本身不是 Flutter 的问题,但在开发中经常遇到,在 Android Pie 版本及以上和 IOS 系统上默认禁止访问 http,主要是为了安全考虑。
Android 解决办法:
在./android/app/src/main/AndroidManifest.xml
配置文件中 application 标签里面设置 networkSecurityConfig 属性:
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<application android:networkSecurityConfig="@xml/network_security_config">
<!-- ... -->
</application>
</manifest>
2
3
4
5
6
在./android/app/src/main/res
目录下创建 xml 文件夹(已存在不用创建),在 xml 文件夹下创建 network_security_config.xml 文件,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
2
3
4
5
6
7
8
# IOS 无法访问 http
在./ios/Runner/Info.plist
文件中添加如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
...
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</dict>
</plist>
2
3
4
5
6
7
8
9
10
11
12
版权所有,禁止私自转发、克隆网站。