老孟导读:今天分享StackOverflow上高访问量的20大问题,这些问题给我一种特别熟悉的感受,我想你必定或多或少的遇到过,有的问题在stackoverflow上有几十万的阅读量,说明不少人都遇到了这些问题,把这些问题整理分享给你们,每期20个,每隔2周分享一次。android
你能够按照以下方式实现:ios
一、Width = Wrap_content Height=Wrap_content:git
Wrap(
children: <Widget>[your_child])
复制代码
二、Width = Match_parent Height=Match_parent:安全
Container(
height: double.infinity,
width: double.infinity,child:your_child)
复制代码
三、Width = Match_parent ,Height = Wrap_conten:markdown
Row(
mainAxisSize: MainAxisSize.max,
children: <Widget>[*your_child*],
);
复制代码
四、Width = Wrap_content ,Height = Match_parent:app
Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[your_child],
);
复制代码
future
方法错误用法:less
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: httpCall(),
builder: (context, snapshot) {
},
);
}
复制代码
正确用法:ide
class _ExampleState extends State<Example> {
Future<int> future;
@override
void initState() {
future = Future.value(42);
super.initState();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: future,
builder: (context, snapshot) {
},
);
}
}
复制代码
在使用底部导航时常常会使用以下写法:函数
Widget _currentBody;
@override
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(() {});
}
复制代码
此用法致使每次切换时都会重建页面。oop
解决办法,使用IndexedStack
:
int _currIndex;
@override
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;
});
}
复制代码
一般状况下,使用TabBarView以下:
TabBarView(
controller: this._tabController,
children: <Widget>[
_buildTabView1(),
_buildTabView2(),
],
)
复制代码
此时切换tab时,页面会重建,解决方法设置PageStorageKey
:
var _newsKey = PageStorageKey('news');
var _technologyKey = PageStorageKey('technology');
TabBarView(
controller: this._tabController,
children: <Widget>[
_buildTabView1(_newsKey),
_buildTabView2(_technologyKey),
],
)
复制代码
在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,
),
)
],
),
),
)
复制代码
此时红色盒子充满父组件,解决办法,给红色盒子组件包裹Center、Align或者UnconstrainedBox,代码以下:
Positioned.fill(
child: Align(
child: Container(
height: 100,
width: 100,
color: Colors.red,
),
),
)
复制代码
class Test extends StatefulWidget {
Test({this.data});
final int data;
@override
State<StatefulWidget> createState() => _TestState();
}
class _TestState extends State<Test>{
}
复制代码
以下,如何在_TestState获取到Test的data
数据呢:
widget.data
(推荐)。上面的异常在类构造函数的时候会常常碰见,以下面的代码就会出现此异常:
class BarrageItem extends StatefulWidget {
BarrageItem(
{ this.text,
this.duration = Duration(seconds: 3)});
复制代码
异常信息提示:可选参数必须为常量,修改以下:
const Duration _kDuration = Duration(seconds: 3);
class BarrageItem extends StatefulWidget {
BarrageItem(
{this.text,
this.duration = _kDuration});
复制代码
定义一个常量,Dart
中常量一般使用k
开头,_
表示私有,只能在当前包内使用,别问我为何如此命名,问就是源代码中就是如此命名的。
MaterialApp(
debugShowCheckedModeBanner: false
)
复制代码
下面的用法是没法显示颜色的:
Color(0xb74093)
复制代码
由于Color的构造函数是ARGB
,因此须要加上透明度,正确用法:
Color(0xFFb74093)
复制代码
FF
表示彻底不透明。
class _FooState extends State<Foo> {
TextEditingController _controller;
@override
void initState() {
super.initState();
_controller = new TextEditingController(text: '初始值');
}
@override
Widget build(BuildContext context) {
return TextField(
controller: _controller,
);
}
}
复制代码
Scaffold.of()中的context没有包含在Scaffold中,以下代码就会报此异常:
class HomePage extends StatelessWidget {
@override
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);
}
复制代码
注意此时的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('老孟'),
),
),
),
);
复制代码
在执行flutter
命令时常常遇到上面的问题,
解决办法一:
一、Mac或者Linux在终端执行以下命令:
killall -9 dart
复制代码
二、Window执行以下命令:
taskkill /F /IM dart.exe
复制代码
解决办法二:
删除flutter SDK的目录下/bin/cache/lockfile
文件。
setState
不能在StatelessWidget控件中调用了,须要在StatefulWidget中调用。
一、使用FractionallySizedBox
控件
二、获取父控件的大小并乘以百分比:
MediaQuery.of(context).size.width * 0.5
复制代码
解决方法:
Row(
children: <Widget>[
Flexible(
child: new TextField(),
),
],
),
复制代码
获取焦点:
FocusScope.of(context).requestFocus(_focusNode);
复制代码
_focusNode
为TextField的focusNode:
_focusNode = FocusNode();
TextField(
focusNode: _focusNode,
...
)
复制代码
失去焦点:
_focusNode.unfocus();
复制代码
import 'dart:io' show Platform;
if (Platform.isAndroid) {
// Android-specific code
} else if (Platform.isIOS) {
// iOS-specific code
}
复制代码
平台类型包括:
Platform.isAndroid
Platform.isFuchsia
Platform.isIOS
Platform.isLinux
Platform.isMacOS
Platform.isWindows
复制代码
其实这自己不是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>
复制代码
在./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>
复制代码
在./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>
复制代码
老孟Flutter博客地址(近200个控件用法):laomengit.com