Flutter在initState方法中获取上下文

waw*_*awa 35 dart flutter

我不确定这是否initState是正确的功能.我想要实现的是检查页面何时呈现以执行某些检查,并根据它们打开a AlertDialog来进行一些设置(如果需要).

我有一个有州的页面.它的initState功能如下:

@override
void initState() {
    super.initState();
    if (!_checkConfiguration()) {
        _showConfiguration(context);
    }
}
Run Code Online (Sandbox Code Playgroud)

_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);
}
Run Code Online (Sandbox Code Playgroud)

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


编辑:它在这里接缝他们有类似的问题:Flutter重定向到initState上的页面

rmt*_*zie 52

上下文在initState期间可用,但您必须包装将对话框推送到Future中的代码,以便它仅在下一帧完成.

这是一个充实的例子:

Future.delayed(Duration.zero,() {
  ... showDialog(context, ....)
}
Run Code Online (Sandbox Code Playgroud)

值得注意的是initState.这是因为在调用构建函数和完成构建函数之间的构建阶段,您无法执行将页面推送到导航器等操作.延迟的未来会在当前运行的代码完成后立即运行代码.

编辑:使用OP的更多上下文,下一部分不再相关.

另一个选择,因为这是在一个页面中完成 - 无论你从哪里推送页面(你必须有一个上下文或你无法推送),你可以从那里检查并打开对话框(或至少公开一个方法)某个地方做推,然后检查).

再次编辑:通过OP的更多上下文,我可以提供更好的解决方案.根据应用程序的不同,您实际上可能希望根据是否是第一次打开应用程序(即设置initState为不同的内容)来决定显示哪个页面.对话框不一定是移动设备上最好的UI元素; 最好显示一个完整的页面,其中包含他们需要添加的设置和下一个按钮.

  • 这真是太糟了.你可以访问上下文的第一个地方是`didChangeDependencies`方法 (4认同)
  • 就我而言,它在 initState 中显示“未定义的名称上下文” (2认同)
  • @rmtmckenzie 函数 Future.delayed(Duration.zero,() {} 总是在 build() 之后运行吗?如果在 initState() 中添加非 Future 或另一个 Future 方法会怎样?您知道吗有什么问题吗?我实现了你的示例,到目前为止效果很好。 (2认同)

Pab*_*rra 21

用包装 Future

  @override
  void initState() {
    super.initState();
    _store = Store();
    new Future.delayed(Duration.zero,() {
      _store.fetchContent(context);
    });
  }
Run Code Online (Sandbox Code Playgroud)


Bay*_*ayu 13

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

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

因此,我选择didChangeDependencies()方法。如已接受的答案中所述,它有一个警告,即它可以在小部件的生命周期中多次调用。然而,它很容易处理。只需使用一个辅助变量bool即可防止在didChangeDependencies(). 以下是使用_BookListState变量_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();
  }

...
}

Run Code Online (Sandbox Code Playgroud)

这是我尝试执行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):
Run Code Online (Sandbox Code Playgroud)