Flutterにて『No Directionality widget found.』が出た時の解決法

 

環境

macOS Big Sur Version 11.5.2

Flutter 2.2.3

XCode 12.5.1

問題

Flutterにてアプリを作成中に以下のようなエラーに遭遇

No Directionality widget found.
RichText widgets require a Directionality widget ancetor.
The specific widget that could not find a Directionality ancestors was RichText.

エラー画面

問題のソースコード

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: const Text("hello!"),
    );
  }
}

Widgetが無いよと怒られている。

StatefulWidgetを実装する時はWidgetを配置しなければならないみたい。しかし、ContainerというWidgetを配置しているのに何故エラーが出力されているのだか。。

正確な理由は分からないが、StatefulWidgetを実装するならContainerだけではダメだということ。

解決方法

MaterialAppとScaffordでラップしてあげ、Textを実装することで解決。

日頃からMaterialデザインかCupertinoデザインを使用することを意識つけることが大事だと考えられる。

import 'package:flutter/material.dart';

void main() => runApp(
      const MaterialApp(
        home: MyApp(),
      ),
    );

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(
        child: Text('Hello Text!'),
      ),
    );
  }
}

コメント

タイトルとURLをコピーしました