Flutter 开发问题:No Directionality widget found.
·
import 'package:flutter/material.dart';
void main(List<String> args) {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return Container(
color: Colors.blue,
alignment: Alignment.center,
child: Container(color: Colors.green, child: Text("test content")),
);
}
}
- 在 Flutter 开发中,执行上述代码,会报错,出现如下错误信息
No Directionality widget found.
RichText widgets require a Directionality widget ancestor.
The specific widget that could not find a Directionality ancestor was:
RichText
The ownership chain for the affected widget is: "RichText ← Text ← ColoredBox ← Container ← Align ←
ColoredBox ← Container ← MyApp ← _FocusInheritedScope ← _FocusScopeWithExternalFocusNode ← ⋯"
Typically, the Directionality widget is introduced by the MaterialApp or WidgetsApp widget at the
top of your application widget tree. It determines the ambient reading direction and is used, for
example, to determine how to lay out text, how to interpret "start" and "end" values, and to resolve
EdgeInsetsDirectional, AlignmentDirectional, and other *Directional objects.
问题原因
-
Text 组件需要在其祖先树中存在一个 Directionality 组件来确定文本的阅读方向(例如,从左到右、从右到左)
-
代码直接使用了 Container 作为根组件,缺少了 MaterialApp 或 WidgetsApp,这些组件会自动提供 Directionality 组件和其他必要的组件
处理策略
- 使用 MaterialApp 组件
import 'package:flutter/material.dart';
void main(List<String> args) {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
home: Container(
color: Colors.blue,
alignment: Alignment.center,
child: Container(color: Colors.green, child: Text("test content")),
),
);
}
}
更多推荐

所有评论(0)