Flutter在initState方法中获取上下文

时间:2018-03-23 20:19:01

标签: dart flutter

我不确定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函数,但无法找到它。

编辑:它在这里接缝时遇到了类似的问题:Flutter Redirect to a page on initState

6 个答案:

答案 0 :(得分:16)

成员变量上下文可以在<table> <tr> <td> <div class="divProp"> <p>DIV 1</p> </div> </td> <td></td> <td> <div class="divProp"> <p>DIV 2</p> </div> </td> <td></td> <td> <div class="divProp"> <p>LONG TEXT DIV 3</p> <p class="noneBold">Sub Div 3</p> </div> </td> <td></td> <td> <div class="divProp"> <p>DIV 4</p> </div> </td> <td></td> <td> <div class="divProp"> <p>DIV 5</p> </div> </td> </tr> </table>期间访问,但不能用于所有内容。这是来自initState文档的扑动:

  

您无法使用此initState   方法。但是,会立即调用[BuildContext.inheritFromWidgetOfExactType]   遵循此方法,[didChangeDependencies]   可以在那里使用。

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

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

一种简单的方法是使用未来。

didChangeDependencies

另一种可能更正确的方法是使用flutter的调度程序添加后帧回调:

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

最后,这是我想在initState函数中使用异步调用的一个小技巧:

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

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

的完全充实的例子
() async {
  await Future.delayed(Duration.zero);
  ... showDialog(context, ...)      
}();

通过评论中提供的OP的更多上下文,我可以为他们的具体问题提供更好的解决方案。根据应用程序的不同,您实际上可能希望根据首次打开应用程序时显示的页面做出决定,即将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, ), ], ), ), ); } } 设置为不同的内容。对话框不一定是移动设备上最好的UI元素;最好显示一个完整的页面,其中包含需要添加的设置和下一个按钮。

答案 1 :(得分:6)

Future

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

答案 2 :(得分:4)

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

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

因此,我选择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();
  }

...
}

当我尝试执行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):

答案 3 :(得分:1)

您必须使用AfterLayout包,只需检出示例即可,它提供了解决此问题的理想方法

https://pub.dartlang.org/packages/after_layout

答案 4 :(得分:1)

我们可以将全局密钥用作:

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),
        ));
      }


}

答案 5 :(得分:0)

简单使用Timer.run()

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