Flutter 在 initState 方法中获取上下文

Flutter get context in initState method

我不确定 initState 是否适合此功能。 我想要实现的是检查页面何时呈现以执行一些检查,并根据它们打开 AlertDialog 以根据需要进行一些设置。

我有一个有状态的页面。 它的 initState 函数如下所示:

@override
void initState() {
    super.initState();
    if (!_checkConfiguration()) {
        _showConfiguration(context);
    }
}

_showConfiguration像这样:

void _showConfiguration(BuildContext context) {
    AlertDialog dialog = new AlertDialog(
        content: new Column(
            children: <Widget>[
                new Text('@todo')
            ],
        ),
        actions: <Widget>[
            new FlatButton(onPressed: (){
                Navigator.pop(context);
            }, child: new Text('OK')),
        ],
    );

    showDialog(context: context, child: dialog);
}

如果有更好的方法来进行此检查并在需要时调用模态,请指出正确的方向,我正在寻找 onStateonRender 函数或回调我可以分配给要在渲染时调用的 build 函数,但找不到一个。


编辑:它接缝在这里他们有一个类似的问题:

成员变量context可以在initState期间访问,但不能用于所有情况。这是来自 flutter for initState 文档:

You cannot use [BuildContext.inheritFromWidgetOfExactType] from this method. However, [didChangeDependencies] will be called immediately following this method, and [BuildContext.inheritFromWidgetOfExactType] can be used there.

您可以将初始化逻辑移动到 didChangeDependencies,但这可能不是您想要的,因为 didChangeDependencies 可以在小部件的生命周期中被多次调用。

如果您改为进行异步调用,委托您的调用直到小部件初始化之后,您就可以按需要使用上下文。

一个简单的方法是使用 future。

Future.delayed(Duration.zero,() {
  ... showDialog(context, ....)
}

另一种方式,可能更'correct',就是利用flutter的scheduler加一个post-frame回调:

SchedulerBinding.instance.addPostFrameCallback((_) {
  ... showDialog(context, ....)
});

最后,这里有一个我喜欢在 initState 函数中使用异步调用的小技巧:

() async {
  await Future.delayed(Duration.zero);
  ... showDialog(context, ...)      
}();

这是一个使用简单 Future.delayed:

的完整示例
import 'dart:async';

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  bool _checkConfiguration() => true;

  void initState() {
    super.initState();
    if (_checkConfiguration()) {
      Future.delayed(Duration.zero,() {
        showDialog(context: context, builder: (context) => AlertDialog(
          content: Column(
            children: <Widget>[
              Text('@todo')
            ],
          ),
          actions: <Widget>[
            FlatButton(onPressed: (){
              Navigator.pop(context);
            }, child: Text('OK')),
          ],
        ));
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
    );
  }
}

有了评论中提供的 OP 的更多上下文,我可以针对他们的特定问题提供稍微更好的解决方案。根据应用程序的不同,您实际上可能想要根据是否是第一次打开应用程序来决定显示哪个页面,即将 home 设置为不同的内容。对话框不一定是移动设备上最好的 UI 元素;显示包含他们需要添加的设置和下一步按钮的完整页面可能会更好。

Future

换行
  @override
  void initState() {
    super.initState();
    _store = Store();
    new Future.delayed(Duration.zero,() {
      _store.fetchContent(context);
    });
  }

简单使用Timer.run()

@override
void initState() {
  super.initState();
  Timer.run(() {
    // you have a valid context here
  });
}

我们可以使用全局密钥作为:

class _ContactUsScreenState extends State<ContactUsScreen> {

    //Declare Global Key
      final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

    //key
    Widget build(BuildContext context) {
        return  Scaffold(
            key: _scaffoldKey,
            appBar: AppBar(
              title: Text('Contact Us'),
            ),
            body:
       }

    //use
      Future<void> send() async {
        final Email email = Email(
          body: _bodyController.text,
          subject: _subjectController.text,
          recipients: [_recipientController.text],
          attachmentPaths: attachments,
          isHTML: isHTML,
        );

        String platformResponse;

        try {
          await FlutterEmailSender.send(email);
          platformResponse = 'success';
        } catch (error) {
          platformResponse = error.toString();
        }

        if (!mounted) return;

        _scaffoldKey.currentState.showSnackBar(SnackBar(
          content: Text(platformResponse),
        ));
      }


}

======更新======

就像Lucas Rueda ( thanks to him :), When we need to get context inside initState() in order to work with "Provider”指出的那样,我们应该将参数listen设置为=false。这是有道理的,因为我们不应该听initState()阶段。因此,例如,它应该是:

final settingData = Provider.of<SettingProvider>(context, listen: false);

=========== 旧答案 =======

该线程中 initState() 的大多数示例可能适用于“UI”事物,例如该线程的根本问题中的“对话框”。

但不幸的是,当应用它为“Provider”获取 context 时,它对我不起作用。

因此,我选择 didChangeDependencies() 方法。正如接受的答案中提到的,它有一个警告,即它可以在小部件的生命周期中被多次调用。但是,它很容易处理。只需使用一个辅助变量 bool 来防止 didChangeDependencies() 中的多次调用。这是 _BookListState class 的示例用法,变量 _isInitialized 作为“多次调用”的主要“阻止者”:

class _BookListState extends State<BookList> {
  List<BookListModel> _bookList;
  String _apiHost;
  bool _isInitialized; //This is the key
  bool _isFetching;

  @override
  void didChangeDependencies() {
    final settingData = Provider.of<SettingProvider>(context);
    this._apiHost = settingData.setting.apiHost;
    final bookListData = Provider.of<BookListProvider>(context);
    this._bookList = bookListData.list;
    this._isFetching = bookListData.isFetching;

    if (this._isInitialized == null || !this._isInitialized) {// Only execute once
      bookListData.fetchList(context);
      this._isInitialized = true; // Set this to true to prevent next execution using "if()" at this root block
    }

    super.didChangeDependencies();
  }

...
}

这是我尝试执行 initState() 方法时的错误日志:

E/flutter ( 3556): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: 'package:provider/src/provider.dart': Failed assertion: line 242 pos 7: 'context.owner.debugBuilding ||
E/flutter ( 3556):           listen == false ||
E/flutter ( 3556):           debugIsInInheritedProviderUpdate': Tried to listen to a value exposed with provider, from outside of the widget tree.
E/flutter ( 3556):
E/flutter ( 3556): This is likely caused by an event handler (like a button's onPressed) that called
E/flutter ( 3556): Provider.of without passing `listen: false`.
E/flutter ( 3556):
E/flutter ( 3556): To fix, write:
E/flutter ( 3556): Provider.of<SettingProvider>(context, listen: false);
E/flutter ( 3556):
E/flutter ( 3556): It is unsupported because may pointlessly rebuild the widget associated to the
E/flutter ( 3556): event handler, when the widget tree doesn't care about the value.
E/flutter ( 3556):
E/flutter ( 3556): The context used was: BookList(dependencies: [_InheritedProviderScope<BookListProvider>], state: _BookListState#1008f)
E/flutter ( 3556):
E/flutter ( 3556): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
E/flutter ( 3556): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
E/flutter ( 3556): #2      Provider.of
package:provider/src/provider.dart:242
E/flutter ( 3556): #3      _BookListState.initState.<anonymous closure>
package:perpus/…/home/book-list.dart:24
E/flutter ( 3556): #4      new Future.delayed.<anonymous closure> (dart:async/future.dart:326:39)
E/flutter ( 3556): #5      _rootRun (dart:async/zone.dart:1182:47)
E/flutter ( 3556): #6      _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter ( 3556): #7      _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter ( 3556): #8      _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
E/flutter ( 3556): #9      _rootRun (dart:async/zone.dart:1190:13)
E/flutter ( 3556): #10     _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter ( 3556): #11     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1021:23)
E/flutter ( 3556): #12     Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter ( 3556): #13     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:397:19)
E/flutter ( 3556): #14     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:428:5)
E/flutter ( 3556): #15     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
E/flutter ( 3556):

这项工作使用方法构建小部件中的键。

首先创建密钥:

  final GlobalKey<NavigatorState> key =
  new GlobalKey<NavigatorState>();

与我们的小部件绑定后:

  @override
  Widget build(BuildContext context) {
    return Scaffold(key:key);
  }

最后我们使用key调用.currentContext参数。

    @override
      void initState() {
        super.initState();
        SchedulerBinding.instance.addPostFrameCallback((_) {
            // your method where use the context
            // Example navigate:
            Navigator.push(key.currentContext,"SiestaPage"); 
        });
   }

编码愉快。