在flutter使用TabController過程中
TabController _tabController;
提示:
Non-nullable instance field '_tabController' must be initialized.
Try adding an initializer expression, or a generative constructor that initializes it, or mark it 'late'.如果_tabController是全局的變量男公,在之前的版本中是不報錯,看到報錯信息已經(jīng)提示了怎么修改磁携,添加修飾詞late氮唯,稍后初始化的意思鉴吹。
“Flutter Late就是Flutter的延遲執(zhí)行函數(shù),它被用來處理延遲執(zhí)行請求,以確保在特定時間之后才會執(zhí)行。這樣就解決報錯了您觉。
然后在initState()方法中初始化
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this);
}
完整代碼:
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
debugShowCheckedModeBanner: false,
title: "TabBar Inside AppBar Demo",
home: TopTabBarAppBarDemo(),
));
class TopTabBarAppBarDemo extends StatefulWidget {
@override
_TopTabBarAppBarDemoState createState() => _TopTabBarAppBarDemoState();
}
class _TopTabBarAppBarDemoState extends State<TopTabBarAppBarDemo>
with SingleTickerProviderStateMixin {
late TabController _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this);
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
Widget getTabBar() {
return TabBar(controller: _tabController, tabs: [
Tab(text: "首頁", icon: Icon(Icons.home)),
Tab(text: "編輯", icon: Icon(Icons.edit)),
Tab(text: "設(shè)置", icon: Icon(Icons.settings)),
]);
}
Widget getTabBarPages() {
return TabBarView(controller: _tabController, children: <Widget>[
Container(
color: Colors.red,
child: Text("首頁",
style: Theme.of(context) //
.primaryTextTheme
.titleLarge),
),
Container(color: Colors.green),
Container(color: Colors.blue)
]);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
flexibleSpace: SafeArea(
child: getTabBar(),
),
),
body: getTabBarPages());
}
}
效果圖:
WeChat513cd35061bed215ca84064dbba033cb.png