我试图在按下按钮时更改应用程序的背景色。但是,当我单击它时会弹出错误。
我尝试将所有东西包装在卡中,放在容器中,放在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.
最佳答案
你得到的原因
这是因为没有父窗口小部件可提供与您提供的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();
},
),
)
),
)
),
);
}
}
关于android - 如何解决 “No Directionality widget found.”问题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57830829/