提问者:小点点

Flutter在initState方法中获取上下文


我不确定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重定向到initState上的页面


共3个答案

匿名用户

成员变量上下文可以在initState期间访问,但不能用于所有事情。这来自initState留档的flutter:

您不能从此方法中使用[BuildContext. in的FromWidgetOfExactType]。但是,[didChangeDependency]将在该方法之后立即调用,并且[BuildContext.in的FromWidgetOfExactType]可以在那里使用。

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

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

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

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

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

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

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

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

这是一个使用简单Future. delay的完全充实的示例:

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

匿名用户

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

就像Lucas Rueda所指出的(感谢他:),当我们需要在initState()中获取context以使用“Provider”时,我们应该将参数设置为=false。这是有道理的,因为我们不应该监听initState()阶段。所以,例如,它应该是:

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

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

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

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

因此,我选择了didChangeDependements()方法。正如公认的答案中提到的,它有一个警告,即它可以在小部件的生命周期中被多次调用。然而,它很容易处理。只需使用单个帮助变量bool来防止didChangeDependency()内部的多次调用。以下是_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):