我试图在按下按钮时更改应用程序的背景颜色。但是,当我单击它时会弹出错误。
我尝试将所有东西包装在卡中,放在容器中,放在Material App中,并添加了setState方法。
import 'package:flutter/material.dart';
void main(){
runApp(
myStateFulWidget(
)
);
}
class myStateFulWidget extends StatefulWidget {
@override
_myStateFulWidgetState createState() => _myStateFulWidgetState();
}
class _myStateFulWidgetState extends State<myStateFulWidget> {
changeColor(){
setState(() {
var colorPart = Colors.red;
});
}
@override
Widget build(BuildContext context) {
return Card(
child:Container(
color: Colors.green,
child: RaisedButton(
color: Colors.black,
child: Text("Ola",textDirection: TextDirection.ltr),
onPressed: (){
changeColor();
},
),
)
);
}
}
我一直遇到的错误是:
════════ Exception Caught By widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown building InkWell(gestures: [tap], clipped to BoxShape.rectangle, dirty, dependencies: [_FocusMarker], state: _InkResponseState<InkResponse>#6fdbb):
No Directionality widget found.
答案 0 :(得分:1)
你得到的理由
No Directionality widget found
例外
是因为没有父窗口小部件可以提供与您提供的RaisedButton
textDirection值一起使用的方向信息。这可以通过提供一个Directionality
小部件或另一个从其上下文中提供TextDirection
信息的部件(例如Scaffold
)来解决。
请注意,背景色仅在其他小部件未覆盖的部分中可见。
import 'package:flutter/material.dart';
void main(){
runApp( MyStatefulWidget());
}
class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
var colorPart = Colors.green;
changeColor(){
setState(() {
colorPart = colorPart == Colors.red ? Colors.green : Colors.red ;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: colorPart,
body: Center(
child: Card(
child:Container(
child: RaisedButton(
//color: Colors.black,
child: Text("Ola",textDirection: TextDirection.ltr),
onPressed: (){
changeColor();
},
),
)
),
)
),
);
}
}
答案 1 :(得分:0)
Try using this :
import 'package:flutter/material.dart';
void main(){
runApp(
myStateFulWidget(
)
);
}
class myStateFulWidget extends StatefulWidget {
@override
_myStateFulWidgetState createState() => _myStateFulWidgetState();
}
class _myStateFulWidgetState extends State<myStateFulWidget> {
Color col = Colors.green;
@override
Widget build(BuildContext context) {
return MaterialApp(
home:new
Scaffold(
backgroundColor:col ,
body:Card(
child: RaisedButton(
child: Text("Ola",textDirection: TextDirection.ltr),
onPressed: (){
changeColor();
},
),
)
)
);
}
changeColor(){
setState(() {
col = Colors.red;
});
}
}
答案 2 :(得分:0)
将var colorPart = Colors.red
声明为setstate以外的状态