未定义的名称“上下文”(在Flutter Navigation中)

时间:2020-07-06 11:08:51

标签: flutter dart

因此,我试图使用Navigator.push(不使用NamedRoutes)从一个屏幕导航到另一个屏幕。但是突然我收到未定义名称“上下文”的错误。我想从“ loading_screen.dart”导航到“ context_screen.dart”。我不明白为什么会遇到此错误。

loading_screen.dart

id data_level var1    var2
aa   h         1       4
bb   l         2       5
cc   l         1.4     4.2
dd   h         1.3     3.8
h    h         2.3     3.9
l    l         3.4     4.6
All  All       5.7     4.25

context_screen.dart

class LoadingScreen extends StatefulWidget {

  String searchTerm;
  LoadingScreen({this.searchTerm});

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


class _LoadingScreenState extends State<LoadingScreen> {

  @override
  void initState() {
    print("On Loading Screen");
    String searchTerm = widget.searchTerm;
    getMeaning(searchTerm);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SpinKitWave(
          color: kMainBlueColor,
          size: 70.0,
        ),
      ),
    );
  }
}

void getMeaning(String searchTerm) async {
  print(searchTerm);
  // TODO: get the meaning of the search term.
  // TODO: Test without net and see background loading
  var searchContext;
  // var searchContext = await .....
  Navigator.push(context, MaterialPageRoute(builder: (context) {
    return ContextScreen(searchContext: searchContext);
  }));
}

我已经忽略了上面的import语句,但是已经在代码中添加了它们。任何帮助,将不胜感激。预先感谢。

2 个答案:

答案 0 :(得分:1)

错误是因为您在initState中调用了使用上下文的方法。context仅在完成initState后可用。

因此,您可以在didChangeDependencies之后立即调用的initState中调用该方法。

要了解有关didChangeDependencies的更多信息:https://api.flutter.dev/flutter/widgets/State/didChangeDependencies.html

要了解有关StatefulWidget生命周期的更多信息:https://medium.com/flutter-community/widget-state-buildcontext-inheritedwidget-898d671b7956

答案 1 :(得分:1)

您可以在下面复制粘贴运行完整代码
您可以将getMeaning移至_LoadingScreenState并使用addPostFrameCallback

代码段

class _LoadingScreenState extends State<LoadingScreen> {
  void getMeaning(String searchTerm) async {
    print(searchTerm);
    // TODO: get the meaning of the search term.
    // TODO: Test without net and see background loading
    var searchContext = "";
    // var searchContext = await .....
    await Future.delayed(Duration(seconds: 5), () {
    });

    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return ContextScreen(searchContext: searchContext);
    }));
  }

  @override
  void initState() {
    print("On Loading Screen");
    String searchTerm = widget.searchTerm;

    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getMeaning(searchTerm);
    });
  }

工作演示

enter image description here

完整代码

import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

class LoadingScreen extends StatefulWidget {
  String searchTerm;
  LoadingScreen({this.searchTerm});

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

class _LoadingScreenState extends State<LoadingScreen> {
  void getMeaning(String searchTerm) async {
    print(searchTerm);
    // TODO: get the meaning of the search term.
    // TODO: Test without net and see background loading
    var searchContext = "";
    // var searchContext = await .....
    await Future.delayed(Duration(seconds: 5), () {
    });

    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return ContextScreen(searchContext: searchContext);
    }));
  }

  @override
  void initState() {
    print("On Loading Screen");
    String searchTerm = widget.searchTerm;

    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getMeaning(searchTerm);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SpinKitWave(
          color: Colors.blue,
          size: 70.0,
        ),
      ),
    );
  }
}

class ContextScreen extends StatefulWidget {
  final searchContext;
  ContextScreen({this.searchContext});

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

class _ContextScreenState extends State<ContextScreen> {
  @override
  Widget build(BuildContext context) {
    var searchContext = widget.searchContext;
    return Scaffold(
        body: SafeArea(
      child: Column(
        children: <Widget>[
          Align(
            alignment: Alignment.topLeft,
            child: FlatButton(
              onPressed: () {
                int count = 0;
                Navigator.of(context).popUntil((context) => count++ >= 2);
              },
              child: Icon(
                Icons.arrow_back_ios,
                color: Colors.blue,
                size: 50.0,
              ),
            ),
          ),
          Center(
            child: Text(searchContext),
          )
        ],
      ),
    ));
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: LoadingScreen(searchTerm: "test"),
    );
  }
}