其他分享
首页 > 其他分享> > No MaterialLocalizations found (Flutter)

No MaterialLocalizations found (Flutter)

作者:互联网

在显示SimpleDialog时候程序报错 No MaterialLocalizations found 没有找到 MaterialLocalizations

 

搜索找到原因 runApp 需要先调用 StatelessWidget 返回一个 MaterialApp实例.

void main() => runApp(MainPage());

class MainPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

 也就是说runApp 直接接受一个 StatefulWidget就会出现这个错误

 

完整代码

import 'package:flutter/material.dart';

void main() => runApp(MainPage());

class MainPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePage createState() {
    return _HomePage(title: '简单对话框组件');
  }
}

enum Department { treasury, state }

class _HomePage extends State<HomePage> {
  _HomePage({Key key, @required this.title});

  final String title;

  ThemeData themeData = new ThemeData.light();
  Future<void> _askedToLead() async {
    switch (await showDialog<Department>(
        context: context,
        builder: (BuildContext context) {
          return SimpleDialog(
            title: const Text('Select assignment'),
            children: <Widget>[
              SimpleDialogOption(
                onPressed: () {
                  Navigator.pop(context, Department.treasury);
                },
                child: const Text('Treasury department'),
              ),
              SimpleDialogOption(
                onPressed: () {
                  Navigator.pop(context, Department.state);
                },
                child: const Text('State department'),
              ),
            ],
          );
        })) {
      case Department.treasury:
        // Let's go.
        // ...
        break;
      case Department.state:
        // ...
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: this.title,
      debugShowCheckedModeBanner: false,
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text(this.title),
        ),
        body: null,
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.format_list_numbered),
          onPressed: _askedToLead,
        ),
      ),
      theme: themeData,
    );
  }
}

 

标签:MaterialLocalizations,return,title,context,new,Department,found,HomePage,Flutter
来源: https://www.cnblogs.com/z45281625/p/10469978.html