老孟導讀:今天分享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