关于我的Flutter代码中的航线代码有什么问题吗?

3hvapo4f  于 2022-11-17  发布在  Flutter
关注(0)|答案(2)|浏览(108)

我想在Flutter中做一个新的路线,但是我失败了,我的VS Code给予我这个:

处理手势时引发了以下Assert:I/扑动(32582):所请求的导航器操作的上下文不包括Navigator. I/flutter(32582):用于从导航器推送或弹出路线的上下文必须是I/flutter小部件的上下文(32582):导航器小部件的后代

import 'package:flutter/material.dart';

void main()=>runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Lake',
      routes: {
        'sss': (context)=>new NewRoute()
      },
      home: new Scaffold(
        appBar: AppBar(
          title: Text('Lake'),
        ),
        body: Text('BBB'),
        floatingActionButton: new FloatingActionButton(
          child: Icon(Icons.import_contacts),
          onPressed: (){
            Navigator.pushNamed(context, 'sss');
          },
        ),
      ),

    );
  }
}

class NewRoute extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return new Scaffold(
      appBar: AppBar(
        title: Text('BBB'),
      ),
      body: Center(
        child: Text('wahaha'),
      ),
    );
  }
}
pjngdqdw

pjngdqdw1#

请使用此代码

home: Builder(
        builder: (context) => Scaffold(
        appBar: AppBar(
          title: Text('Lake'),
        ),
        body: Text('BBB'),
        floatingActionButton: new FloatingActionButton(
          child: Icon(Icons.import_contacts),
          onPressed: (){
            Navigator.pushNamed(context, 'sss');
          },
        ),
      ),)

构建器允许您从直接父项构建新上下文,如https://docs.flutter.io/flutter/widgets/Builder-class.html所述

c9qzyr3d

c9qzyr3d2#

您正在错误地使用路径。当您在MaterialApp中使用主页时,它将绕过路径。您可以使用initialRoute来定义主页屏幕,而不是

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Lake',
      routes: {
        'sss': (context) => const NewRoute(),
        'home': (context) => const HomeScreen(),
      },
      initialRoute: 'home',
    );
  }
}

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Lake'),
      ),
      body: const Text('BBB'),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.import_contacts),
        onPressed: () {
          Navigator.pushNamed(context, 'sss');
        },
      ),
    );
  }
}

class NewRoute extends StatelessWidget {
  const NewRoute({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BBB'),
      ),
      body: const Center(
        child: Text('wahaha'),
      ),
    );
  }
}

也避免使用新的关键字。你也可以尝试在flutter中使用onGenarated Routes。more information

相关问题