请求的StatefulWidget:Navigator操作在不包含Navigator的上下文中

时间:2018-12-06 13:58:07

标签: dart flutter statefulwidget

我正在尝试创建示例,并试图从statefulWidget创建导航,但出现以下错误,大多数示例都在谈论无状态小部件之间的导航

flutter: ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
flutter: The following assertion was thrown while handling a gesture:
flutter: Navigator operation requested with a context that does not include a Navigator.
flutter: The context used to push or pop routes from the Navigator must be that of a widget that is a
flutter: descendant of a Navigator widget.

下面是我的代码

import 'package:flutter/material.dart';
import 'package:flutter_app/second.dart';

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

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  var strings = ["Flutter", "Java", "SWift"];
  var displayText = "";

  void onPressed() {
    var list = List<int>.generate(3, (int index) => index); // [0, 1, 4]
    list.shuffle();
    print(list);

    setState(() {
      displayText = strings[list.first];
    });
  }

  @override
  Widget build(BuildContext context) {
    var scaffold = Scaffold(
      appBar: AppBar(
        title: Text('Flutter Second'),
      ),
      body: Container(
          child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              displayText,
              style: TextStyle(
                  color: Colors.red,
                  fontStyle: FontStyle.normal,
                  fontWeight: FontWeight.bold,
                  fontSize: 30.0),
            ),
            Padding(
              padding: EdgeInsets.all(10.0),
            ),
            RaisedButton(
              child: Text('Change'),
              textColor: Colors.black,
              onPressed: () {
                Navigator.pushNamed(context, '/second'); // Fails here
              },
            )
          ],
        ),
      )),
    );
    return MaterialApp(
      home: scaffold,
      routes: {
        '/second': (context) => SecondScreen(),
      },
    );
  }
}

下面是我尝试过的

  1. 使用了Navigator.of(context)

  2. statefulwidget封装为通过无状态小工具创建的材质应用的首页。

但没有运气。

0 个答案:

没有答案