我的标签栏视图中有两个无状态小组件,我的应用程序运行正常。但是随后需要在其中一个视图中制作一个按钮并更改按钮的状态,因此我将其作为有状态小部件进行了设置,但是现在选项卡栏视图不接受它,并在运行该“类型”时给出了例外任务”不是“ StatelessWidget”类型的子类型。 TabBar视图中只能有无状态小组件吗?我怎样才能解决这个问题?
我的具有TabBarview的main.dart文件
import 'package:flutter/material.dart';
import 'package:flutter_convertor/task.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: DefaultTabController(length: 2,child: MyHomePage(title: '')),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context){
final list = ListView.builder(
itemBuilder: (context, position) {
//some other implementation
},
);
return Scaffold(
appBar: AppBar(
title: Text('Home'), bottom: TabBar(
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.directions_transit)),
]),
),
body: TabBarView(children: [list, task()]));
}
}
我的状态小部件任务
class task extends StatefulWidget{
@override
taskState createState() => new taskState();
}
class taskState extends State<task> {
int current_step = 0;
bool isButtonDisabled;
@override void initState() {
super.initState();
isButtonDisabled = false;
}
formReady(){
setState(() {
isButtonDisabled = !isButtonDisabled ;
});
}
@override
Widget build(BuildContext context) {
Column taskScreen = Column(
children: <Widget>[Expanded(
child: ListView(
children: <Widget>[
//other implementation
FlatButton(
color: Colors.red,
textColor: Colors.black,
shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(20.0)),
disabledColor: Color(0XFFf9c3c1),
disabledTextColor: Colors.white,
padding: EdgeInsets.all(8.0),
splashColor: Colors.red[400],
onPressed: isButtonDisabled ? null : _completePage
,
child: Text(
"Completed",
style: TextStyle(color: Colors.white, fontSize: 15.0, fontWeight: FontWeight.bold),
),
)
,
],
)
]);
return taskScreen;
}
}
答案 0 :(得分:0)
您需要使用AutomaticKeepAliveClientMixin
才能正常工作。这是一个相当简单的mixin使用。您只需要包含
@override
bool get wantKeepAlive => true;
并将super.build(context)
添加到您的构建方法中。
您更新后的类如下所示:
class task extends StatefulWidget{
@override
taskState createState() => new taskState();
}
class taskState extends State<task> with AutomaticKeepAliveClientMixin<task>
@override
Widget build(BuildContext context) {
super.build(context);
...
}
}