dart 在initState方法中获取上下文

eni9jsuy  于 2022-12-20  发布在  其他
关注(0)|答案(6)|浏览(136)

我不确定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

ykejflvf

ykejflvf1#

成员变量context可以在initState期间访问,但不能用于所有的操作,这来自flutter for initState文档:
不能从此方法中使用[BuildContext.inheritFromWidgetOfExactType]。但是,将在此方法之后立即调用[didChangeDependencies],并且可以在此方法中使用[BuildContext.inheritFromWidgetOfExactType]
您可以将初始化逻辑移到didChangeDependencies,但是这可能不是您想要的,因为didChangeDependencies在小部件的生命周期中可能被多次调用。
如果您改为进行异步调用,将调用委托到小部件初始化之后,那么您就可以按照自己的意愿使用上下文。
一个简单的方法就是利用未来。

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

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

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元素;最好显示一个完整的页面,上面有他们需要添加的设置和一个下一步按钮。

frebpwbc

frebpwbc2#

Future Package

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

4jb9z9bj3#

=====已更新======

正如Lucas Rueda所指出的(感谢他:),当我们需要在initState()中得到context以便处理“Provider“时,我们应该将参数listen设置为= false,这是有意义的,因为我们不应该监听initState()阶段。

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

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

这个线程中initState()的大多数例子可能是“UI”的作品,比如“对话框”,这是这个线程的根本问题。
但不幸的是,当我应用它来获取“Provider“的context时,它不起作用。
因此,我选择了didChangeDependencies()方法,正如在公认的答案中提到的,它有一个警告,即在小部件的生命周期中可以多次调用它。它很容易处理,只需使用一个helper变量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):
gywdnpxw

gywdnpxw4#

使用简单Timer.run()

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

zysjyyx45#

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

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

}
polhcujo

polhcujo6#

这是使用方法构建小部件中的键来完成的。
首先创建密钥:

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

在我们绑定小工具后:

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

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

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

编程愉快。

相关问题